100% found this document useful (1 vote)
10 views

MongoDB for Java developers design build and deliver efficient Java applications using the most advanced NoSQL database Francesco instant download

The document is a promotional overview of the book 'MongoDB for Java Developers' by Francesco Marchioni, which focuses on designing, building, and delivering efficient Java applications using MongoDB, a leading NoSQL database. It includes details about the author's background, the book's contents, and various chapters covering topics such as CRUD operations, Java integration, and using MongoDB with frameworks like Spring and Hibernate. Additionally, it provides links to other related technical books and resources available for download.

Uploaded by

canilbootyhg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
10 views

MongoDB for Java developers design build and deliver efficient Java applications using the most advanced NoSQL database Francesco instant download

The document is a promotional overview of the book 'MongoDB for Java Developers' by Francesco Marchioni, which focuses on designing, building, and delivering efficient Java applications using MongoDB, a leading NoSQL database. It includes details about the author's background, the book's contents, and various chapters covering topics such as CRUD operations, Java integration, and using MongoDB with frameworks like Spring and Hibernate. Additionally, it provides links to other related technical books and resources available for download.

Uploaded by

canilbootyhg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

MongoDB for Java developers design build and

deliver efficient Java applications using the


most advanced NoSQL database Francesco download

https://ebookname.com/product/mongodb-for-java-developers-design-
build-and-deliver-efficient-java-applications-using-the-most-
advanced-nosql-database-francesco/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Oracle Database Programming using Java and Web Services


1st Edition Kuassi Mensah

https://ebookname.com/product/oracle-database-programming-using-
java-and-web-services-1st-edition-kuassi-mensah/

Learn Objective C for Java Developers 1st Edition James


Bucanek

https://ebookname.com/product/learn-objective-c-for-java-
developers-1st-edition-james-bucanek/

Professional Eclipse 3 for Java Developers 1st Edition


Berthold Daum

https://ebookname.com/product/professional-eclipse-3-for-java-
developers-1st-edition-berthold-daum/

HTML Professional Projects 4th Edition John W. Gosney

https://ebookname.com/product/html-professional-projects-4th-
edition-john-w-gosney/
The AH Receptor in Biology and Toxicology 1rst edition
Edition Raimo Pohjanvirta

https://ebookname.com/product/the-ah-receptor-in-biology-and-
toxicology-1rst-edition-edition-raimo-pohjanvirta/

Key buildings from prehistory to the present Plans


sections and elevations Andrew Ballantyne

https://ebookname.com/product/key-buildings-from-prehistory-to-
the-present-plans-sections-and-elevations-andrew-ballantyne/

Lectures on the History of Moral and Political


Philosophy Jonathan Wolff

https://ebookname.com/product/lectures-on-the-history-of-moral-
and-political-philosophy-jonathan-wolff/

Essentials of Foreign Exchange Trading Essentials


Series 1st Edition James Chen

https://ebookname.com/product/essentials-of-foreign-exchange-
trading-essentials-series-1st-edition-james-chen/

One Hundred Plus Deck Designs Single Level Decks Multi


Level Decks L Shaped Decks and Many More Home Planners

https://ebookname.com/product/one-hundred-plus-deck-designs-
single-level-decks-multi-level-decks-l-shaped-decks-and-many-
more-home-planners/
Ion Implantation and Activation Volume 2 1st Edition
Kunihiro Suzuki

https://ebookname.com/product/ion-implantation-and-activation-
volume-2-1st-edition-kunihiro-suzuki/
MongoDB for Java Developers

Design, build, and deliver efficient Java applications


using the most advanced NoSQL database

Francesco Marchioni

BIRMINGHAM - MUMBAI
MongoDB for Java Developers

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: August 2015

Production reference: 1070815

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78528-027-6

www.packtpub.com
Credits

Author Project Coordinator


Francesco Marchioni Shweta Birwatkar

Reviewers Proofreader
Daniel Mühlbachler Safis Editing
Weiwei Sun
Mehdi Tazi Indexer
Tejal Soni

Commissioning Editor
Veena Pagare Production Coordinator
Aparna Bhagat

Acquisition Editors
James Jones Cover Work
Aparna Bhagat
Nadeem N. Bagban

Content Development Editor


Neeshma Ramakrishnan

Technical Editor
Bharat Patil

Copy Editors
Merilyn Pereira
Laxmi Subramanian
About the Author

Francesco Marchioni is a Red Hat Certified JBoss Administrator (RHCJA)


and a Sun Certified enterprise architect working as a freelancer in Rome, Italy.
He started learning Java in 1997, and since then, he has followed the path to the
newest application program interfaces released by Sun. In 2000, he joined the
JBoss community, when the application server was running the release 2.X.

He has spent many years as a software consultant, wherein he envisioned many


successful software migrations from vendor platforms to open source products
such as JBoss AS, fulfilling the tight budget requirements of current times.

Over the past 5 years, he has been authoring technical articles for OReilly Media and
running an IT portal focused on JBoss products (http://www.mastertheboss.com).

In December 2009, he published JBoss AS 5 Development, which describes how to


create and deploy Java Enterprise applications on JBoss AS (http://www.packtpub.
com/jboss-as-5-development/book).

In December 2010, he published his second title, JBoss AS 5 Performance Tuning,


which describes how to deliver fast and efficient applications on JBoss AS
(http://www.packtpub.com/jboss-5-performance-tuning/book).

In December 2011, he published yet another title, JBoss AS 7 Configuration, Deployment,


and Administration, which covers all the aspects of the newest application server
release (http://www.packtpub.com/jboss-as-7-configuration-deployment-
administration/book).

In June 2013, he authored a new title, JBoss AS 7 Development, which focuses on


developing Java EE 6 API applications on JBoss AS 7 (https://www.packtpub.com/
application-development/jboss-7-development).
About the Reviewers

Daniel Mühlbachler got interested in computer science shortly after entering


high school, where he later developed web applications as part of a scholarship
system for outstanding pupils.

He has profound knowledge of web development (PHP, HTML, CSS/LESS, and


AngularJS), and has worked with a variety of other programming languages and
systems, such as Java/Groovy, Grails, Objective-C and Swift, Matlab, C (with Cilk),
Node.js, and Linux servers.

Furthermore, he works with some database management systems based on SQL


and also some NoSQL systems, such as MongoDB and SOLR; this is also reflected
in several projects that he is currently involved in at Catalysts GmbH.

After studying abroad as an exchange student in the United Kingdom, he completed


his bachelor's degree at the Johannes Kepler University in Linz, Austria, with a thesis
on aerosol satellite data processing for mobile visualization; this is where he also
became familiar with processing large amounts of data.

Daniel enjoys solving challenging problems and is always keen on working with new
technologies, especially related to the fields of big data, functional programming,
optimization, and NoSQL databases.

More detailed information about his experience , as well as his contact details, can be
found at www.muehlbachler.org and www.linkedin.com/in/danielmuehlbachler.
Weiwei Sun is a student of Southeast University, China, and also a student of
Monash University, Australia. He also has a double master's degree in computer
technology and information technology. He loves technology, programming, and
open source projects.

His research interests are database technology, data visualization, and application of
machine learning.

You can read more about him at http://wwsun.github.com.

Mehdi Tazi is a software engineer specializing in distributed information systems


and agile project management.

His core expertise involves managing agile scrum teams, as well as architecting
new solutions, and working with multiple technologies, such as JAVA/JEE, Spring,
MongoDB, Cassandra, HTML5, Bootstrap, and AngularJS.

He has a degree in software engineering and a master's degree in business


informatics. He also has several certifications, such as Core-Spring, MongoDB,
Cassandra, and Scrum Master Official.

You can read more about him at http://tazimehdi.com.


www.PacktPub.com

Support files, eBooks, discount offers, and more


For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.
com and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at service@packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles,


sign up for a range of free newsletters and receive exclusive discounts and offers
on Packt books and eBooks.
TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.
This book is dedicated to all the guys that patiently answered my questions
on MongoDB forums and to my son Alessandro that taught me
how to play 'Magic the Gathering' while waiting for replies
Table of Contents
Preface v
Chapter 1: Introduction to MongoDB 1
Getting into the NoSQL movement 1
Comparing RDBMS and NoSQL databases 4
Living without transactions 6
Managing read-write concurrency 7
MongoDB core elements 8
The heart of MongoDB – the document 9
Understanding how MongoDB stores data 10
Data types accepted in documents 11
Installing and starting MongoDB 12
Installing MongoDB on Windows 12
Installing MongoDB on Linux 13
MongoDB start up options 14
Troubleshooting MongoDB installation 15
Mongo tools 16
Introduction to the MongoDB shell 18
Inserting documents 19
Querying documents 19
Choosing the keys to return 20
Using ranges in your queries 21
Using logical operators to query data 22
Updating documents 22
Deleting data 24
Beyond basic data types 25
Arrays 25
Embedded documents 26
Some useful functions 27
Securing database access 28
Summary 30
[i]
Table of Contents

Chapter 2: Getting Started with Java Driver for MongoDB 31


Getting the Mongo JDBC driver 31
Creating your first project 32
Creating a new Java project 32
Handling authentication 35
Inserting a document 36
Creating embedded documents 38
Inserting an array of data 38
Using your own ID in documents 40
Querying data 41
Restricting the search to the first document 43
Querying the number of documents in a collection 43
Eager fetching of data using DBCursor 43
Filtering through the records 44
Updating documents 45
Deleting documents 46
Deleting a set of documents 47
Performing operations on collections 47
Listing collections 48
Dropping a collection 49
Using the MongoDB Java driver version 3 49
Running the HelloWorld class with driver v.3 50
Managing collections 51
Inserting data into the database 51
Inserting embedded documents 52
Inserting multiple documents 53
Querying documents 53
Filtering through documents 54
Updating documents 55
Deleting documents 56
Summary 56
Chapter 3: MongoDB CRUD Beyond the Basics 57
Seeing MongoDB through the Java lens 57
Extending the MongoDB core classes 58
Using the Gson API with MongoDB 62
Downloading the Gson API 62
Using Gson to map a MongoDB document 63
Inserting Java objects as a document 65
Mapping embedded documents 66
Custom field names in your Java classes 68
Mapping complex BSON types 69
Using indexes in your applications 72
Defining an index in your Java classes 75
Using compound indexes 77

[ ii ]
Table of Contents

Using text indexes in your documents 80


Coding bulk operations 83
Comparing plain inserts with BulkWriteOperations 84
Summary 85
Chapter 4: MongoDB in the Java EE 7 Enterprise Environment 87
Entering into the Java EE land 87
Getting a Java EE Container 89
Downloading WildFly 89
Starting WildFly and testing the installation 90
Designing our application 90
Designing the schema 91
Building up the Enterprise project with NetBeans 92
Configuring WildFly on NetBeans 92
Creating our project 94
Adding Java classes 99
Compiling and deploying the project 107
Compiling and deploying from the shell 107
Running the application 108
Exposing the application to external clients 109
Adding RESTful web services to our application 109
Compiling and deploying the application 112
Summary 113
Chapter 5: Managing Data Persistence with
MongoDB and JPA 115
An overview of the Java Persistence API 115
Entering Hibernate OGM 117
Building a JPA project that uses Hibernate OGM 119
Configuring the project dependencies 121
Mapping the database collections 122
Configuring persistence 125
Coding the controller and EJB classes 126
Hibernate OGM and JP-QL 128
Coding a controller bean 129
Coding the views 131
The main view 132
The newCustomer view 133
The newOrder view 134
Compiling and running the example 135
A look into MongoDB 137
Using native queries in your Hibernate OGM 138
Summary 139

[ iii ]
Table of Contents

Chapter 6: Building Applications for MongoDB with


Spring Data 141
Introducing Spring Boot 141
Getting started with Spring Boot 142
Getting started with Spring Data 143
Using the Spring repository to access MongoDB 144
Coding our Spring Boot application 145
Serving MongoDB using Spring REST 153
Using the Mongo template component to access MongoDB 157
Building up the data access layer 157
Adding the Application class 160
Creating fine grained queries using Criteria 161
Summary 163
Index 165

[ iv ]
Preface
The NoSQL movement is growing in relevance, and it is attracting more and more
developers. The MongoDB database is a well-recognized rising star in the NoSQL
world. It is a document database that allows data to persist and query data in a
nested state without any schema constraint and complex joins between documents.
Understanding when it is appropriate to use MongoDB against a relational database
and the interfaces to be used to interact with it requires some degree of experience.

This book provides all the knowledge to make MongoDB fit into your application
schema, at the best of its capabilities. It starts from a basic introduction to the driver
that can be used to perform some low level interaction with the storage. Then it
moves on to use different patterns for abstracting the persistence layer into your
applications, starting from the flexible Google JSON library, to the Hibernate OGM
framework, and finally landing on the Spring Data framework.

What this book covers


Chapter 1, Introduction to MongoDB, covers the installation steps of MongoDB and its
client tools and how to use the Mongo shell to perform basic database operations.

Chapter 2, Getting Started with Java Driver for MongoDB, introduces the Java
Driver for MongoDB using a simple Java project developed with the NetBeans
development environment.

Chapter 3, MongoDB CRUD Beyond the Basics, covers the advanced usage of the
MongoDB Java driver such as data mapping, index creation, and bulk operations.

Chapter 4, MongoDB in the Java EE 7 Enterprise Environment, demonstrates how to


create and deploy a Java Enterprise application that uses MongoDB as the storage.

[v]
Preface

Chapter 5, Managing Data Persistence with MongoDB and JPA, covers the development
of a Java Enterprise application using Hibernate Object/Grid Mapper (OGM), which
provides Java Persistence API (JPA) support for NoSQL databases.

Chapter 6, Building Applications for MongoDB with Spring Data, teaches you how
to use Spring Data and Spring Boot to leverage micro services using MongoDB
as the storage.

What you need for this book


The following software will be needed to run the examples contained in this book:

• Java Development Kit 1.7 or newer


• Mongo DB 2.6 or newer
• MongoDB JDBC Driver 2 and 3
• The NetBeans development environment (or equivalent)

All the software mentioned is freely available for downloading.

Who this book is for


This book is for Java developers and architects who want to learn how to develop
Java applications using the most popular NoSQL solution and its use cases.

Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"In command prompt, navigate to the bin directory present into the mongodb
installation folder and point to the folder where data is stored."

A block of code is set as follows:


MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "test" );
System.out.println("Successfully connected to MongoDB");

[ vi ]
Preface

When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "test" );
System.out.println("Successfully connected to MongoDB");

Any command-line input or output is written as follows:


> db.users.find({}).sort({"name":1})

{ "_id" : ObjectId("5506d5708d7bd8471669e674"), "name" : "francesco",


"age" : 44, "phone" : "123-456-789" }
{ "_id" : ObjectId("550ad3ef89ef057ee0671652"), "name" : "owen", "age" :
32, "phone" : "555-444-333" }

New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: " Now let's
add a Java class to the project. From the File menu, select Java Class under New ".

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to feedback@packtpub.com,


and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.

[ vii ]
Preface

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code


You can download the example code files for all Packt books you have purchased
from your account at http://www.packtpub.com. If you purchased this book
elsewhere, you can visit http://www.packtpub.com/support and register to have
the files e-mailed directly to you.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books—maybe a mistake in the text or the
code—we would be grateful if you would report this to us. By doing so, you can save
other readers from frustration and help us improve subsequent versions of this book.
If you find any errata, please report them by visiting http://www.packtpub.com/
submit-errata, selecting your book, clicking on the errata submission form link,
and entering the details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded on our website, or added to any list
of existing errata, under the Errata section of that title. Any existing errata can be
viewed by selecting your title from http://www.packtpub.com/support.

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected


pirated material.

We appreciate your help in protecting our authors, and our ability to bring you
valuable content.

Questions
You can contact us at questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.
[ viii ]
Chapter 1

Introduction to MongoDB
In this book, you will learn how to develop Java applications using the MongoDB
database, which is an open source document-oriented database, recognized as a
rising star in the NoSQL world. In a nutshell, MongoDB is a document database,
which allows data to persist in a nested state, and importantly, it can query that
nested data in an ad hoc fashion. It enforces no schema, so documents can optionally
contain fields or types that no other document in the collection contains.

The focus of this book is on applications development; however, we will at first


gather all the resources to connect to MongoDB and add a quick introduction to
the world of NoSQL databases. We will cover the following topics in more detail:

• A bird's eye view of the NoSQL landscape


• Installing MongoDB and client tools
• Using the MongoDB shell

Getting into the NoSQL movement


NoSQL is a generic term used to refer to any data store that does not follow the
traditional RDBMS model—specifically, the data is nonrelational and it generally
does not use SQL as a query language. Most of the databases that are categorized
as NoSQL focus on availability and scalability in spite of atomicity or consistency.

This seems quite a generic definition of NoSQL databases; however, all databases
that fall into this category have some characteristics in common such as:

• Storing data in many formats: Almost all RDBMS databases are based on
the storage or rows in tables. NoSQL databases, on the other hand, can use
different formats such as document stores, graph databases, key-value stores
and even more.

[1]
Introduction to MongoDB

• Joinless: NoSQL databases are able to extract your data using simple
document-oriented interfaces without using SQL joins.
• Schemaless data representation: A characteristic of NoSQL implementations
is that they are based on a schemaless data representation, with the notable
exception of the Cassandra database (http://cassandra.apache.org/).
The advantage of this approach is that you don't need to define a data
structure beforehand, which can thus continue to change over time.
• Ability to work with many machines: Most NoSQL systems buy you the
ability to store your database on multiple machines while maintaining
high-speed performance. This brings the advantage of leveraging low cost
machines with separate RAM and disk and also supports linear scalability.

On the other hand, all database developers and administrators know the ACID
acronym. It says that database transactions should be:

• Atomicity: Everything in a transaction either succeeds or is rolled back


• Consistency: Every transaction must leave the database in a consistent state
• Isolation: Each transaction that is running cannot interfere with other
transactions
• Durability: A completed transaction gets persisted, even after
applications restart

At first glance, these qualities seem vital. In practice, however, for many
applications, they are incompatible with the availability and performance in
very large environments. As an example, let's suppose that you have developed an
online book store and you want to display how many of each book you have in your
inventory. Each time a user is in the process of buying a book, you need to lock part
of the database until they finish so that every visitors from the world will see the
exact inventory numbers. That works just fine for a small homemade site but not if
you run Amazon.com. For this reason, when we talk about NoSQL databases, or,
generally, if we are designing distributed systems, we might have to look beyond the
traditional ACID properties. As stated by the CAP theorem, coined by Eric Brewer,
the following set of requirements are truly essential when designing applications for
distributed architectures:

• Consistency: This means the database mostly remains adherent to its rules
(constraints, triggers, and so on) after the execution of each operation and
that any future transaction will see the effects of the earlier transactions
committed. For example, after executing an update, all the clients see the
same data.
• Availability: Each operation is guaranteed a response—a successful or failed
execution. This, in practice, means no downtime.

[2]
Chapter 1

• Partition tolerance: This means the system continues to function even if the
communication among the servers is temporarily unreliable (for example, the
servers involved in the transaction may be partitioned into multiple groups,
which cannot communicate with one another).

In practice, as it is theoretically impossible to have all three requirements met, a


combination of two must be chosen and this is usually the deciding factor in what
technology is used, as shown in the following figure:

If you are designing a typical web application that uses a SQL database, most likely,
you are in the CA part of the diagram. This is because a traditional RDBMS is
typically transaction-based (C) and it can be highly available (A). However, it cannot
be Partition Tolerance (P) because SQL databases tend to run on single nodes.

MongoDB, on the other hand, is consistent by default (C). This means if you perform
a write on the database followed by a read, you will be able to read the same data
(assuming that the write was successful).

Besides consistency, MongoDB leverages Partition Tolerance (P) by means of replica


sets. In a replica set, there exists a single primary node that accepts writes, and
asynchronously replicates a log of its operations to other secondary databases.

[3]
Introduction to MongoDB

However, not all NoSQL databases are built with the same focus. An example of
this is CouchDB. Just like MongoDB, it is document oriented and has been built to
scale across multiple nodes easily; on the other hand, while MongoDB (CP) favors
consistency, CouchDB favors availability (AP) in spite of consistency. CouchDB uses
a replication model called Eventual Consistency. In this model, clients can write
data to one database node without waiting for acknowledgment from other nodes.
The system takes care to copy document changes between nodes, so that they can
eventually be in sync.

The following table summarizes the most common NoSQL databases and their
position relative to CAP attributes:

Database Consistent, Partition- Available, Partition-Tolerant


Tolerant (CP) (AP)
BigTable X
Hypertable X
HBase X
MongoDB X
Terrastore X
Redis X
Scalaris X
MemcacheDB X
Berkeley DB X
Dynamo X
Voldemort X
Tokyo Cabinet X
KAI X
Cassandra X
CouchDB X
SimpleDB X
Riak X

Comparing RDBMS and NoSQL databases


As you might guess, there is no absolute winner between traditional databases and
the new NoSQL standard. However, we can identify a set of pros and cons related to
each technology. This can lead to a better understanding of which one is most fit for
our scenarios. Let's start from traditional RDBMS:

[4]
Chapter 1

RDBMS pros RDBMS cons


ACID transactions at the database level The object-relational mapping layer can be
make development easier. complex.
Fine-grained security on columns and RDBMS doesn't scale out when joins are
rows using views prevents views and required.
changes by unauthorized users. Most SQL
code is portable to other SQL databases,
including open source options.
Typed columns and constraints will Sharding over many servers can be done
validate data before it's added to the but requires application code and will be
database and increase data quality. operationally inefficient.
The existing staff members are already Full-text search requires third-party tools.
familiar with entity-relational design and
SQL.
Well-consolidated theoretical basis and Storing high-variability data in tables can be
design rules. challenging.

The following is a table that contains the advantages and disadvantages of NoSQL
databases:

NoSQL pros NoSQL cons


It can store complex data types (such as There is a lack of server-side transactions;
documents) in a single item of storage. therefore, it is not fit for inherently
transactional systems.
It allows horizontal scalability, which does Document stores do not provide fine-grained
not require you to set up complex joins security at the element level.
and data can be easily partitioned and
processed in parallel.
It saves on development time as it is NoSQL systems are new to many staff
not required to design a fine-grained members and additional training may
data model. be required.
It is quite fast for inserting new data and The document store has its own proprietary
for simple operations or queries. nonstandard query language, which
prohibits portability.
It provides support for Map/Reduce, There is an absence of standardization. No
which is a simple paradigm that allows standard APIs or query languages. It means
for scaling computation on a cluster of that migration to a solution from different
computing nodes. vendors is more costly. Also, there are no
standard tools (for example, for reporting).

[5]
Introduction to MongoDB

Living without transactions


As you can imagine, one of the most important factors when deciding to use
MongoDB or traditional RDBMS is the need for transactions.

With an RDBMS, you can update the database in sophisticated ways using SQL and
wrap multiple statements in a transaction to get atomicity and rollback. MongoDB
doesn't support transactions. This is a solid tradeoff based on MongoDB's goal of
being simple, fast, and scalable. MongoDB, however, supports a range of atomic
update operations that can work on the internal structures of a complex document.
So, for example, by including multiple structures within one document (such as
arrays), you can achieve an update in a single atomic way, just like you would do
with an ordinary transaction.

As documents can grow in complexity and contain several nested


documents, single-document atomicity can be used as a replacement
for transactions in many scenarios.

On the other hand, operations that includes multiple documents (often referred to as
multi-document transactions), are conversely not atomic.

In such scenarios, when you need to synchronize multi-document transactions, you


can implement the 2PC (two-phase commit) in your application so that you can
provision these kinds of multidocument updates. Discussing about this pattern,
however, is out of the scope of this book, but if you are eager to know more, you
can learn more from http://docs.mongodb.org/manual/tutorial/perform-
two-phase-commits/.

So, to sum it up, if your application's requirements can be met via document updates
(also by using nested documents to provide an atomic update), then this is a perfect
use case for MongoDB, which will allow a much easier horizontal scaling of your
application.

On the other hand, if strict transaction semantics (such as a banking application) are
required, then nothing can beat a relational database. In some scenarios, you can
combine both approaches (RDBMS and MongoDB) to get the best of both worlds,
at the price of a more complex infrastructure to maintain. Such hybrid solutions are
quite common; however, you can see them in production apps such as the New York
Times website.

[6]
Discovering Diverse Content Through
Random Scribd Documents
It seemed better to parrot the Belgian and order "Bock," and that
was what I decided to do.
One item on the bill of fare tantalized me considerably. Although it
was listed among the "Prizzen der dranken," which I took to mean
"Prices of drinks," it sounded very much to me like something to eat,
and Heaven knows I would rather have had one honest mouthful of
food than all the drinks in the world. The item I refer to was "Dubbel
Gersten de Flesch (Michaux)." A double portion of anything would
have been mighty welcome to me, but I would have been quite
contented with a single "Gersten"—whatever that might happen to
be—if I had only had the courage to ask for it.
To keep myself as composed as possible, I devoted a lot of attention
to that bill of fare, and I think by the time the waiter came around I
almost knew it by heart. One drink that almost made me laugh out
loud was listed as "Lemonades Gazeuses," but I might just as well
have introduced myself to the German officers by my right name and
rank as to have attempted to pronounce it.
When the waiter came to me, therefore, I said "Bock" as casually as
I could, and felt somewhat relieved that I got through this part of
the ordeal so easily.
While the waiter was away I had a chance to examine the bill of
fare, and I observed that a glass of beer cost eighty centimes. The
smallest change I had was a two-mark paper bill.
Apparently the German officers were similarly fixed, and when they
offered their bill to the waiter he handed it back to them with a
remark which I took to mean that he couldn't make change.
Right there I was in a quandary. To offer him my bill after he had
just told the officers he didn't have change would have seemed
strange, and yet I couldn't explain to him that I was in the same
boat and he would have to come to me again later. The only thing to
do, therefore, was to offer him the bill as though I hadn't heard or
noticed what had happened with the Germans, and I did so. He said
the same thing to me as he had said to the officers, perhaps a little
more sharply, and gave me back the bill. Later on he returned to the
table with a handful of change and we closed the transaction. I gave
him twenty-five centimes as a tip—I had never yet been in a place
where it was necessary to talk to do that.
During my first half-hour in that theater, to say I was on pins and
needles is to express my feelings mildly. The truth of the matter is I
was never so uneasy in my life. Every minute seemed like an hour,
and I was on the point of getting up and leaving a dozen times.
There were altogether too many soldiers in the place to suit me, and
when the German officers seated themselves right at my table I
thought that was about all I could stand. As it was, however, the
lights went out shortly afterward and in the dark I felt considerably
easier.
After the first picture, when the lights went up again, I had regained
my composure considerably and I took advantage of the opportunity
to study the various types of people in the place.
From my seat I had a splendid chance to see them all. At one table
there was a German medical corps officer with three Red Cross
nurses. That was the only time I had ever seen a German nurse, for
when I was in the hospital I had seen only men orderlies. Nurses
don't work so near the first-line trenches.
The German soldiers at the different tables were very quiet and
orderly. They drank Bock beer and conversed among themselves,
but there was no hilarity or rough-housing of any kind.
As I sat there, within an arm's reach of those German officers and
realized what they would have given to know what a chance they
had to capture an escaped British officer, I could hardly help smiling
to myself, but when I thought of the big risk I was taking, more or
less unnecessarily, I began to wonder whether I had not acted
foolishly in undertaking it.
Nevertheless, the evening passed off uneventfully, and when the
show was over I mixed with the crowd and disappeared, feeling very
proud of myself and with a good deal more confidence than I had
enjoyed at the start.
I had passed a night which will live in my life as long as I live. The
bill of fare, program, and a "throw-away" bill advertising the name of
the attraction which was to be presented the following week, which
was handed to me as I came out, I still have and they are among
the most valued souvenirs of my adventure.
XV
O B S E R VAT I O N S I N A B E LG I A N C I TY
One night, shortly before I left this city, our airmen raided the place.
I didn't venture out of the house at the time, but the next night I
thought I would go out and see what damage had been done.
When it became dark I left the house, accordingly, and, mixing with
the crowd, which consisted largely of Germans, I went from one
place to another to see what our "strafing" had accomplished.
Naturally I avoided speaking to any one. If a man or woman
appeared about to speak to me, I just turned my head and looked or
walked away in some other direction. I must have been taken for an
unsociable sort of individual a good many times, and if I had
encountered the same person twice I suppose my conduct might
have aroused suspicion.
I had a first-class observation of the damage that was really done by
our bombs. One bomb had landed very near the main railroad
station, and if it had been only thirty yards nearer would have
completely demolished it. As the station was undoubtedly our
airman's objective, I was very much impressed with the accuracy of
his aim. It is by no means an easy thing to hit a building from the air
when you are going at anywhere from fifty to one hundred miles an
hour and are being shot at from beneath from a dozen different
angles—unless, of course, you are taking one of those desperate
chances and flying so low that you cannot very well miss your mark,
and the Huns can't very well miss you, either!
I walked by the station and mingled with the crowds which stood in
the entrances. They paid no more attention to me than they did to
real Belgians, and the fact that the lights were all out in this city at
night made it impossible, anyway, for any one to get as good a look
at me as if it had been light.
During the time that I was in this city I suppose I wandered from
one end of it to the other. In one place, where the German staff had
its headquarters, a huge German flag hung from the window, and I
think I would have given ten years of my life to have stolen it. Even
if I could have pulled it down, however, it would have been
impossible for me to have concealed it, and to have carried it away
with me as a souvenir would have been out of the question.
As I went along the street one night a lady standing on the comer
stopped me and spoke to me. My first impulse, of course, was to
answer her, explaining that I could not understand, but I stopped
myself in time, pointed to my ears and mouth, and shook my head,
indicating that I was deaf and dumb, and she nodded
understandingly and walked on. Incidents of this kind were not
unusual, and I was always in fear that the time would come when
some inquisitive and suspicious German would encounter me and
not be so easily satisfied.
There are many things that I saw in this city which, for various
reasons, it is impossible for me to relate until after the war is over.
Some of them, I think, will create more surprise than the incidents I
am free to reveal now.
It used to amuse me, as I went along the streets of this town,
looking in the shop windows, with German soldiers at my side
looking at the same things, to think how close I was to them and
they had no way of knowing. I was quite convinced that if I were
discovered my fate would have been death, because I not only had
the forged passport on me, but I had been so many days behind the
German lines after I had escaped that they couldn't safely let me live
with the information I possessed.
One night I walked boldly across a park. I heard footsteps behind
me and, turning around, saw two German soldiers. I slowed up a
trifle to let them get ahead of me. It was rather dark and I got a
chance to see what a wonderful uniform the German military
authorities have picked out. The soldiers had not gone more than a
few feet ahead of me when they disappeared in the darkness like
one of those melting pictures on the moving-picture screen.
As I wandered through the streets I frequently glanced in the café
windows as I passed. German officers were usually dining there, but
they didn't conduct themselves with anything like the light-
heartedness which characterizes the Allied officers in London and
Paris. I was rather surprised at this, because in this part of Belgium
they were much freer than they would have been in Berlin, where, I
understand, food is comparatively scarce and the restrictions are
very rigid.
As I have said, my own condition in this city was in some respects
worse than it had been when I was making my way through the
open country. While I had a place to sleep and my clothes were no
longer constantly soaking, my opportunities for getting food were
considerably less than they had been. Nearly all the time I was half
famished, and I decided that I would get out of there at once, since
I was entirely through with Huyliger.
My physical condition was greatly improved. While the lack of food
showed itself on me, I had regained some of my strength, my
wounds were healed, my ankle was stronger, and, although my
knees were still considerably enlarged, I felt that I was in better
shape than I had been at any time since my leap from the train, and
I was ready to go through whatever was in store for me.
XVI
I APPROACH THE FRONTIER
To get out of the city it would be necessary to pass two guards. This
I had learned in the course of my walks at night, having frequently
traveled to the city limits with the idea of finding out just what
conditions I would have to meet when the time came for me to
leave.
A German soldier's uniform, however, no longer worried me as it had
at first. I had mingled with the Huns so much in the city that I began
to feel that I was really a Belgian, and I assumed the indifference
that the latter seemed to feel.
I decided, therefore, to walk out of the city in the daytime when the
sentries would be less apt to be on the watch. It worked splendidly. I
was not held up a moment, the sentries evidently taking me for a
Belgian peasant on his way to work.
Traveling faster than I had ever done before since my escape, I was
soon out in the open country, and the first Belgian I came to I
approached for food. He gave me half his lunch and we sat down on
the side of the road to eat it. Of course, he tried to talk to me, but I
used the old ruse of pretending I was deaf and dumb and he was
quite convinced that it was so. He made various efforts to talk to me
in pantomime, but I could not make out what he was getting at, and
I think he must have concluded that I was not only half-starved,
deaf, and dumb, but "luny" into the bargain.
When night came I looked around for a place to rest. I had decided
to travel in the daytime as well as night, because I understood that I
was only a few miles from the frontier, and I was naturally anxious
to get there at the earliest possible moment, although I realized that
there I would encounter the most hazardous part of my whole
adventure. To get through that heavily guarded barbed and
electrically charged barrier was a problem that I hated to think of,
even, although the hours I spent endeavoring to devise some way of
outwitting the Huns were many.
It had occurred to me, for instance, that it would not be such a
difficult matter to vault over the electric fence, which was only nine
feet high. In college, I know, a ten-foot vault is considered a high-
school boy's accomplishment, but there were two great difficulties in
the way of this solution. In the first place, it would be no easy
matter to get a pole of the right length, weight, and strength to
serve the purpose. More particularly, however, the pole-vault idea
seemed to be out of the question because of the fact that on either
side of the electric fence, six feet from it, was a six-foot barbed-wire
barrier. To vault safely over a nine-foot electrically charged fence was
one thing, but to combine with it a twelve-foot broad vault was a
feat which even a college athlete in the pink of condition would be
apt to flunk. Indeed, I don't believe it is possible.
Another plan that seemed half-way reasonable was to build a pair of
stilts about twelve or fourteen feet high and walk over the barriers
one by one. As a youngster I had acquired considerable skill in stilt-
walking, and I have no doubt that with the proper equipment it
would have been quite feasible to have walked out of Belgium as
easily as possible in that way, but whether or not I was going to
have a chance to construct the necessary stilts remained to be seen.
There were a good many bicycles in use by the German soldiers in
Belgium, and it had often occurred to me that if I could have stolen
one, the tires would have made excellent gloves and insulated
coverings for my feet in case it was necessary for me to attempt to
climb over the electric fence bodily. But as I had never been able to
steal a bicycle, this avenue of escape was closed to me.
I decided to wait until I arrived at the barrier and then make up my
mind how to proceed.
To find a decent place to sleep that night I crawled under a barbed-
wire fence, thinking it led into some field. As I passed under, one of
the barbs caught in my coat, and in trying to pull myself free I shook
the fence for several yards.
Instantly there came out of the night the nerve-racking command,
"Halt!"
Again I feared I was done for. I crouched close down on the ground
in the darkness, not knowing whether to take to my legs and trust to
the Hun's missing me in the darkness if he fired, or stay right where
I was. It was foggy as well as dark, and although I knew the sentry
was only a few feet away from me I decided to stand, or rather lie
still. I think my heart made almost as much noise as the rattling of
the wire in the first place, but it was a tense few moments for me.
I heard the German say a few words to himself, but didn't
understand them, of course, and then he made a sound as if to call
a dog, and I realized that his theory of the noise he had heard was
that a dog had made its way through the fence.
For perhaps five minutes I didn't stir, and then, figuring that the
German had probably continued on his beat, I crept quietly under
the wire again, this time being mighty careful to hug the ground so
close that I wouldn't touch the wire, and made off in a different
direction. Evidently the barbed-wire fence had been thrown around
an ammunition-depot or something of the kind and it was not a field
at all that I had tried to get into.
I figured that other sentries were probably in the neighborhood and
I proceeded very gingerly.
After I had got about a mile away from this spot I came to a humble
Belgian house, and I knocked at the door and applied for food in my
usual way, pointing to my mouth to indicate I was hungry and to my
ears and mouth to imply that I was deaf and dumb. The Belgian
woman who lived in the house brought me a piece of bread and two
cold potatoes, and as I sat there eating them she eyed me very
keenly.
I haven't the slightest doubt that she realized I was a fugitive. She
lived so near the border that it was more than likely that other
fugitives had come to her before, and for that reason I appreciated
more fully the extent of the risk she ran, for no doubt the Germans
were constantly watching the conduct of these Belgians who lived
near the line.
My theory that she realized that I was not a Belgian at all, but
probably some English fugitive, was confirmed a moment later
when, as I made ready to go, she touched me on the arm and
indicated that I was to wait a moment. She went to a bureau and
brought out two pieces of fancy Belgian lace, which she insisted
upon my taking away, although at that particular moment I had as
much use for Belgian lace as an elephant has for a safety-razor, but I
was touched with her thoughtfulness and pressed her hand to show
my gratitude. She would not accept the money I offered her.
I carried that lace through my subsequent experiences, feeling that
it would be a fine souvenir for my mother, although, as a matter of
fact, if she had known that it was going to delay my final escape for
even a single moment, as it did, I am quite sure she would rather I
had never seen it.
On one piece of lace was the Flemish word "Charité" and on the
other the word "Espérance." At the time, I took these words to mean
"Charity" and "Experience," and all I hoped was that I would get as
much of the one as I was getting of the other before I finally got
through. I learned subsequently that what the words really stood for
was "Charity" and "Hope," and then I was sure that my kind Belgian
friend had indeed realized my plight and that her thoughtful souvenir
was intended to encourage me in the trials she must have known
were before me.
I didn't let the old Belgian lady know, because I did not want to
alarm her unnecessarily, but that night I slept in her backyard,
leaving early in the morning before it became light.
Later in the day I applied at another house for food. It was occupied
by a father and mother and ten children. I hesitated to ask them for
food without offering to pay for it, as I realized what a task it must
have been for them to support themselves without having to feed a
hungry man. Accordingly, I gave the man a mark and then indicated
that I wanted something to eat. They were just about to eat,
themselves, apparently, and they let me partake of their meal, which
consisted of a huge bowl of some kind of soup which I was unable
to identify and which they served in ordinary wash-basins! I don't
know that they ever used the basins to wash in as well, but whether
they did or not did not worry me very much. The soup was good and
I enjoyed it very much.
All the time I was there I could see the father and the eldest son, a
boy about seventeen, were extremely nervous. I had indicated to
them that I was deaf and dumb, but if they believed me it didn't
seem to make them any more comfortable.
I lingered at the house for about an hour after the meal, and during
that time a young man came to call on the eldest daughter, a young
woman of perhaps eighteen. The caller eyed me very suspiciously,
although I must have resembled anything but a British officer. They
spoke in Flemish and I did not understand a word they said, but I
think they were discussing my probable identity. During their
conversation, I had a chance to look around the rooms. There were
three altogether, two fairly large and one somewhat smaller, about
fourteen feet long and six deep. In this smaller room there were two
double-decked beds, which were apparently intended to house the
whole family, although how the whole twelve of them could sleep in
that one room will ever remain a mystery to me.
From the kitchen you could walk directly into the cow-barn, where
two cows were kept, and this, as I have pointed out before, is the
usual construction of the poorer Belgian houses.
I could not make out why the caller seemed to be so antagonistic to
me, and yet I am sure he was arguing with the family against me.
Perhaps the fact that I wasn't wearing wooden shoes—I doubt
whether I could have obtained a pair big enough for me—had
convinced him that I was not really a Belgian, because there was
nothing about me otherwise which could have given him that idea.
At that time—and I suppose it is true to-day—about ninety per cent.
of the people in Belgium were wearing wooden shoes. Among the
peasants I don't believe I ever saw any other kind of footwear, and
they are more common there than they are in Holland. The Dutch
wear them more as a matter of custom. In Belgium they are a dire
necessity because of the lack of leather. I was told that during the
coming year practically all the peasants and poorer people in
Germany, too, will adopt wooden shoes for farm-work, as that is one
direction in which wood can be substituted for leather without much
loss.
When the young man left I left shortly afterward, as I was not at all
comfortable about what his intentions were regarding me. For all I
knew, he might have gone to notify the German authorities that
there was a strange man in the vicinity—more, perhaps, to protect
his friends from suspicion of having aided me than to injure me.
At any rate, I was not going to take any chances and I got out of
that neighborhood as rapidly as I could.
That night found me right on the frontier of Holland.
XVII
G E TT I N G T H R O U G H T H E L I N E S
Waiting until it was quite dark, I made my way carefully through a
field and eventually came to the much-dreaded barrier.
It was all that I had heard about it. Every foot of the border-line
between Belgium and Holland is protected in precisely the same
manner. It is there to serve three purposes: first, to keep the
Belgians from escaping into Holland; second, to keep enemies, like
myself, from making their way to freedom; and, third, to prevent
desertions on the part of Germans themselves. One look at it was
enough to convince any one that it probably accomplished all three
objects about as well as any contrivance could, and one look was all
I got of it that night, for while I lay on my stomach gazing at the
forbidding structure I heard the measured stride of a German sentry
advancing toward me, and I crawled away as fast as I possibly
could, determined to spend the night somewhere in the fields and
make another and more careful survey the following night.
The view I had obtained, however, was sufficient to convince me
that the pole-vault idea was out of the question even if I had a pole
and were a proficient pole-vaulter. The three fences covered a span
of at least twelve feet, and to clear the last barbed-wire fence it
would be necessary to vault not only at least ten feet high, but at
least fourteen feet wide, with certain knowledge that to touch the
electrically charged fence meant instant death. There would be no
second chance if you came a cropper the first time.
The stilt idea was also impracticable because of the lack of suitable
timber and tools with which to construct the stilts.
It seemed to me that the best thing to do was to travel up and down
the line a bit in the hope that some spot might be discovered where
conditions were more favorable, although I don't know just what I
expected along those lines.
It was mighty disheartening to realize that only a few feet away lay
certain liberty and that the only thing that prevented me from
reaching it were three confounded fences. I thought of my machine
and wished that some kind fairy would set it in front of me for just
one minute.
I spent the night in a clump of bushes and kept in hiding most of the
next day, only going abroad for an hour or two in the middle of the
day to intercept some Belgian peasant and beg for food. The
Belgians in this section were naturally very much afraid of the
Germans, and I fared badly. In nearly every house German soldiers
were quartered, and it was out of the question for me to apply for
food in that direction. The proximity of the border made every one
eye one another with more or less suspicion, and I soon came to the
conclusion that the safest thing I could do was to live on raw
vegetables, which I could steal from the fields at night as I had
previously done.
That night I made another survey of the barrier in that vicinity, but it
looked just as hopeless as it had the night before, and I concluded
that I only wasted time there.
I spent the night wandering west, guided by the North Star, which
had served me so faithfully in all my traveling. Every mile or two I
would make my way carefully to the barrier to see if conditions were
any better, but it seemed to be the same all along. I felt like a wild
animal in a cage, with about as much chance of getting out.
The section of the country in which I was now wandering was very
heavily wooded and there was really no very great difficulty in
keeping myself concealed, which I did all day long, striving all the
time to think of some way in which I could circumvent that cursed
barrier.
The idea of a huge step-ladder occurred to me, but I searched hour
after hour in vain for lumber or fallen trees out of which I could
construct one. If I could only obtain something which would enable
me to reach a point about nine feet in the air, it would be a
comparatively simple matter to jump from that point over the
electric fence.
Then I thought that perhaps I could construct a simple ladder and
lean it against one of the posts upon which the electric wires were
strung, climb to the top and leap over, getting over the barbed-wire
fences in the same way.
This seemed to be the most likely plan, and all night long I sat
constructing a ladder for this purpose.
I was fortunate enough to find a number of fallen pine-trees from
ten to twenty feet long. I selected two of them which seemed
sufficiently strong and broke off all the branches, which I used as
rungs, tying them to the poles with grass and strips from my
handkerchief and shirt as best I could.
It was not a very workmanlike-looking ladder when I finally got
through with it. I leaned it against a tree to test it and it wabbled
considerably. It was more like a rope ladder than a wooden one, but
I strengthened it here and there and decided that it would probably
serve the purpose.
I kept the ladder in the woods all day and could hardly wait until
dark to make the supreme test. If it proved successful, my troubles
were over; within a few hours I would be in a neutral country out of
all danger. If it failed—I dismissed the idea summarily. There was no
use worrying about failure; the thing to do was to succeed.
The few hours that were to pass before night came on seemed
endless, but I utilized them to reinforce my ladder, tying the rungs
more securely with long grass which I plucked in the woods.
At last night came, and with my ladder in hand I made for the
barrier. In front of it there was a cleared space of about one hundred
yards, which had been prepared to make the work of the guards
easier in watching it.
I waited in the neighborhood until I heard the sentry pass the spot
where I was in hiding, and then I hurried across the clearing, shoved
my ladder under the barbed wire, and endeavored to follow it. My
clothing caught in the wire, but I wrenched myself clear and crawled
to the electric barrier.
My plan was to place the ladder against one of the posts, climb up
to the top, and then jump. There would be a fall of nine or ten feet,
and I might possibly sprain my ankle or break my leg, but if that was
all that stood between me and freedom I wasn't going to stop to
consider it.
I put my ear to the ground to listen for the coming of the sentry.
There was not a sound. Eagerly but carefully I placed the ladder
against the post and started up. Only a few feet separated me from
liberty, and my heart beat fast.
I had climbed perhaps three rungs of my ladder when I became
aware of an unlooked-for difficulty.
The ladder was slipping!
Just as I took the next rung the ladder slipped, came in contact with
the live wire, and the current passed through the wet sticks and into
my body. There was a blue flash, my hold on the ladder relaxed, and
I fell heavily to the ground unconscious!
Of course, I had not received the full force of the current or I would
not now be here. I must have remained unconscious for a few
moments, but I came to just in time to hear the German guard
coming, and the thought came to me that if I didn't get that ladder
concealed at once, he would see it even though, fortunately for me,
it was an unusually dark night.
I pulled the ladder out of his path and lay down flat on the ground,
not seven feet away from his beat. He passed so close that I could
have pushed the ladder out and tripped him up.
It occurred to me that I could have climbed back under the barbed-
wire fence and waited for the sentry to return and then felled him
with a blow on the head, as he had no idea, of course, that there
was any one in the vicinity. I wouldn't have hesitated to take life,
because my only thought now was to get into Holland, but I thought
that as long as he didn't bother me perhaps the safest thing to do
was not to bother him, but to continue my efforts during his periodic
absences.
His beat at this point was apparently fairly long and allowed me
more time to work than I had hoped for.
My mishap with the ladder had convinced me that escape in that
way was not feasible. The shock that I had received had unnerved
me and I was afraid to risk it again, particularly as I realized that I
had fared more fortunately than I could hope to again if I met with a
similar mishap. There was no way of making that ladder hold, and I
gave up the idea of using it.
I was now right in front of this electric barrier, and as I studied it I
saw another way of getting by. If I couldn't get over it, what was the
matter with getting under it?
The bottom wire was only two inches from the ground, and, of
course, I couldn't touch it, but my plan was to dig underneath it and
then crawl through the hole in the ground.
I had only my hands to dig with, but I went at it with a will, and
fortunately the ground was not very hard.
When I had dug about six inches, making a distance in all of eight
inches from the lowest electric wire, I came to an underground wire.
I knew enough about electricity to realize that this wire could not be
charged, as it was in contact with the ground, but still there was not
room between the live wire and this underground wire for me to
crawl through, and I either had to go on digging deep enough under
this wire to crawl under it or else pull it up.
This underground wire was about as big around as a lead-pencil and
there was no chance of breaking it. The jack-knife I had had at the
start of my travels I had long since lost, and even if I had had
something to hammer with, the noise would have made that method
impracticable.
I went on digging. When the total distance between the live wire
and the bottom of the hole I had dug was thirty inches I took hold of
the ground wire and pulled on it with all my strength.
It wouldn't budge. It was stretched taut across the narrow ditch I
had dug—about fourteen inches wide—and all my tugging didn't
serve to loosen it.
I was just about to give it up in despair when a staple gave way in
the nearest post. This enabled me to pull the wire through the
ground a little, and I renewed my efforts. After a moment or two of
pulling as I had never pulled in my life before a staple on the next
post gave way, and my work became easier. I had more leeway now
and pulled and pulled again until in all eight staples had given way.
Every time a staple gave way it sounded in my ears like the report of
a gun, although I suppose it didn't really make very much noise.
Nevertheless, each time I would put my ear to the ground to listen
for the guard, and, not hearing him, went on with my work.
By pulling on the wire I was now able to drag it through the ground
enough to place it back from the fence and go on digging.
The deeper I went the harder became the work, because by this
time my finger-nails were broken and I was nervous—afraid every
moment that I would touch the charged wire.
I kept at it, however, with my mind constantly on the hole I was
digging and the liberty which was almost within my reach.
Finally I figured that I had enough space to crawl through and still
leave a couple of inches between my back and the live wire.
Before I went under that wire I noticed that the lace which the
Belgian woman had given me as a souvenir made my pocket bulge,
and lest it might be the innocent means of electrocuting me by
touching the live wire, I took it out, rolled it up, and threw it over
the barrier.
Then I lay down on my stomach and crawled or rather writhed
under the wire like a snake, with my feet first, and there wasn't any
question of my hugging Mother Earth as closely as possible, because
I realized that even to touch the wire above me with my back meant
instant death.
Anxious as I was to get on the other side, I didn't hurry this
operation. I feared that there might be some little detail that I had
overlooked, and I exercised the greatest possible care in going
under, taking nothing for granted.
When I finally got through and straightened up there were still
several feet of Belgium between me and liberty, represented by the
six feet which separated the electric barrier from the last barbed-
wire fence, but before I went another step I went down on my
knees and thanked God for my long series of escapes and especially
for this last achievement, which seemed to me to be about all that
was necessary to bring me freedom.
Then I crawled under the barbed-wire fence and breathed the free
air of Holland! I had no clear idea just where I was, and I didn't
much care. I was out of the power of the Germans, and that was
enough. I had walked perhaps a hundred yards when I remembered
the lace I had thrown over the barrier, and, dangerous as I realized
the undertaking to be, I determined to walk back and get it. This
necessitated my going back on to Belgian soil again, but it seemed a
shame to leave the lace there, and by exercising a little care I
figured I could get it easily enough.
When I came to the spot at which I had made my way under the
barbed wire I put my ear to the ground and listened for the sentry. I
heard him coming and lay prone on the ground till he had passed.
The fact that he might observe the hole in the ground or the ladder
occurred to me as I lay there, and it seemed like an age before he
finally marched out of earshot. Then I went under the barbed wire
again, retrieved the lace, and once again made my way to Dutch
territory.
It does not take long to describe the events just referred to, but the
incidents themselves consumed several hours in all. To dig the hole
must have taken me more than two hours, and I had to stop
frequently to hide while the sentry passed. Many times, indeed, I
thought I heard him coming and stopped my work, and then
discovered that it was only my imagination. I certainly suffered
enough that night to last me a lifetime. With a German guard on one
side, death from electrocution on the other, and starvation staring
me in the face, my plight was anything but a comfortable one.
It was the 19th of November, 1917, when I got through the wires. I
had made my leap from the train on September 9th. Altogether,
therefore, just seventy-two days had elapsed since I escaped from
the Huns. If I live to be as old as Methuselah, I never expect to live
through another seventy-two days so crammed full of incident and
hazard and lucky escapes.
XVIII
E X P E R I E N C E S I N H O L LA N D
But I was not yet quite out of the woods.
I now knew that I was in Holland, but just where I had no idea. I
walked for about thirty minutes and came to a path leading to the
right, and I had proceeded along it but a few hundred yards when I
saw in front of me a fence exactly like the one I had crossed.
"This is funny," I said to myself. "I didn't know the Dutch had a
fence, too." I advanced to the fence and examined it closely, and
judge of my astonishment when I saw beyond it a nine-foot fence
apparently holding live wires exactly like the one which had nearly
been the death of me!
I had very little time to conjecture what it all meant, for just then I
heard a guard coming. He was walking so fast that I was sure it was
a Dutch sentry, as the Huns walk much more slowly.
I was so bewildered, however, that I decided to take no chances,
and as the road was fairly good I wandered down it and away from
that mysterious fence. About half a mile down I could see the light
of a sentry station, and I thought I would go there and tell my story
to the sentries, realizing that as I was unarmed it was perfectly safe
for me to announce myself to the Dutch authorities. I could be
interned only if I entered Holland under arms.
As I approached the sentry box I noticed three men in gray
uniforms, the regulation Dutch color. I was on the verge of shouting
to them when the thought struck me that there was just a chance I
might be mistaken, as the German uniforms were the same color,
and I had suffered too many privations and too many narrow
escapes to lose all at this time.
I had just turned off the road to go back into some bushes when out
of the darkness I heard that dread German command:
"Halt! Halt!"
He didn't need to holler twice. I heard and heeded the first time.
Then I heard another man come running up, and there was
considerable talking, but whether they were Germans or Hollanders I
was still uncertain. Evidently, however, he thought the noise must be
a dog or the wind.
Finally I heard one of them laugh and heard him walk back to the
sentry station where the guard was billeted, and I crawled a little
nearer to try to make out just what it all meant. I had begun to think
it was all a nightmare.
Between myself and the light in the sentry station I then noticed the
stooping figure of a man bending over as if to conceal himself, and
on his head was the spiked helmet of a German soldier!
I knew then what another narrow escape I had had, for I am quite
sure he would have shot me without ceremony if I had foolishly
made myself known. I would have been buried at once and no one
would have been any the wiser, even though, technically speaking, I
was on neutral territory and immune from capture or attack.
This new shock only served to bewilder me the more. I was
completely lost. There seemed to be frontier behind me and frontier
in front of me. Evidently, however, what had happened was that I
had lost my sense of direction and had wandered in the arc of a
circle, returning to the same fence that I had been so long in getting
through. This solution of the mystery came to me suddenly, and I at
once searched the landscape for something in the way of a landmark
to guide me. For once my faithful friend, the North Star, had failed
me. The sky was pitch black and there wasn't a star in the heavens.
In the distance, at what appeared to be about three miles away, but
which turned out to be six, I could discern the lights of a village, and
I knew that it must be a Dutch village, as lights are not allowed in
Belgium in that indiscriminate way.
My course was now clear. I would make a bee-line for that village.
Before I had gone very far I found myself in a marsh or swamp, and
I turned back a little, hoping to find a better path. Finding none, I
retraced my steps and kept straight ahead, determined to reach that
village at all costs and to swerve neither to the right nor to the left
until I got there.
One moment I would be in water up to my knees and the next I
would sink in clear up to my waist. I paid no attention to my
condition. It was merely a repetition of what I had gone through
many times before, but this time I had a definite goal, and, once I
reached it, I knew my troubles would be over.
It took me perhaps three hours to reach firm ground. The path I
struck led to within half a mile of the village. I shall never forget that
path; it was almost as welcome to my feet as the opposite bank of
the Meuse had seemed.
The first habitation I came to was a little workshop with a bright
light shining outside. It must have been after midnight, but the
people inside were apparently just quitting work. There were three
men and two boys engaged in making wooden shoes.
It wasn't necessary for me to explain to them that I was a refugee,
even if I had been able to speak their language. I was caked with
mud up to my shoulders, and I suppose my face must have recorded
some of the experiences I had gone through that memorable night.
"I want the British consul," I told them.
Apparently they didn't understand, but one of them volunteered to
conduct me to the village. They seemed to be only too anxious to do
all they could for me; evidently they realized I was a British soldier.
It was very late when my companion finally escorted me into the
village, but he aroused some people he knew from their beds and
they dressed and came down to feed me.
The family consisted of an old lady and her husband and a son who
was a soldier in the Dutch army. The cold shivers ran down my back
while he sat beside me, because every now and again I caught a
glimpse of his gray uniform and it resembled very much that of the
German soldiers.
Some of the neighbors, aroused by the commotion, got up to see
what it was all about, and came in and watched while I ate the meal
those good Dutch people prepared for me. Ordinarily, I suppose, I
would have been embarrassed with so many people staring at me
while I ate, as though I were some strange animal that had just
been captured, but just then I was too famished to notice or care
very much what other people did.
There will always be a warm place in my heart for the Dutch people.
I had heard lots of persons say that they were not inclined to help
refugees, but my experience did not bear these reports out. They
certainly did much more for me than I ever expected.
I had a little German money left, but as the value of German money
is only about half in Holland, I didn't have enough to pay the fare to
Rotterdam, which was my next objective. It was due to the
generosity of these people that I was able to reach the British consul
as quickly as I did. Some day I hope to return to Holland and repay
every single soul who played the part of Good Samaritan to me.
With the money that these people gave me I was able to get a third-
class ticket to Rotterdam, and I am glad that I didn't have enough to
travel first-class, for I would have looked as much out of place in a
first-class carriage as a Hun would appear in heaven.
That night I slept in the house of my Dutch friends, where they fixed
me up most comfortably. In the morning they gave me breakfast
and then escorted me to the station.
While I was waiting in the station a crowd gathered round me, and
soon it seemed as if the whole town had turned out to get a look at
me. It was very embarrassing, particularly as I could give them no
information regarding the cause of my condition, although, of
course, they all knew that I was a refugee from Belgium.
As the train pulled out of the station the crowd gave a loud cheer,
and the tears almost came to my eyes as I contrasted in my mind
the conduct of this crowd and the one that had gathered at the
station in Ghent when I had departed a prisoner en route for the
reprisal camp. I breathed a sigh of relief as I thought of that reprisal
camp and how fortunate I had really been, despite all my suffering,
to have escaped it. Now, at any rate, I was a free man and I would
soon be sending home the joyful news that I had made good my
escape.
At Einhoffen two Dutch officers got into the compartment with me.
They looked at me with very much disfavor, not knowing, of course,
that I was a British officer. My clothes were still pretty much in the
condition they were when I crossed the border, although I had been
able to scrape off some of the mud I had collected the night before.
I had not shaved nor trimmed my beard for many days, and I must
have presented a sorry appearance. I could hardly blame them for
edging away from me.
The trip from Einhoffen to Rotterdam passed without special
incident. At various stations passengers would get into the
compartment and, observing my unusual appearance, would
endeavor to start a conversation with me. None of them spoke
English, however, and they had to use their own imagination as to
my identity.
When I arrived at Rotterdam I asked a policeman who stood in front
of the station where I could find the British consul, but I could not
make him understand. I next applied to a taxicab driver.
"English consul—British consul—American consul—French consul," I
said, hoping that if he didn't understand one he might recognize
another.
He eyed me with suspicion and motioned me to get in and drove off.
I had no idea where he was taking me, but after a quarter of an
hour's ride he brought up in front of the British consulate. Never
before was I so glad to see the Union Jack!
I beckoned to the chauffeur to go with me up to the office, as I had
no money with which to pay him, and when we got to the consulate
I told them that if they would pay the taxi fare I would tell them who
I was and how I happened to be there.
They knew at once that I was an escaped prisoner and they readily
paid the chauffeur and invited me to give some account of myself.
They treated me most cordially and were intensely interested in the
brief account I gave them of my adventures. Word was sent to the
consul-general, and he immediately sent for me. When I went in he
shook hands with me, greeting me very heartily and offering me a
chair.
He then sat down, screwed a monocle on his eye, and viewed me
from top to toe. I could see that only good breeding kept him from
laughing at the spectacle I presented. I could see he wanted to
laugh in the worst way.
"Go ahead and laugh!" I said. "You can't offend me the way I feel
this blessed day!" And he needed no second invitation. Incidentally,
it gave me a chance to laugh at him, for I was about as much
amused as he was.
After he had laughed himself about sick he got up and slapped me
on the back and invited me to tell him my story.
"Lieutenant," he said, when I had concluded, "you can have
anything you want. I think your experiences entitle you to it."
"Well, Consul," I replied, "I would like a bath, a shave, a hair-cut,
and some civilized clothes about as badly as a man ever needed
them, I suppose, but before that I would like to get a cable off to
America to my mother, telling her that I am safe and on my way to
England."
The consul gave the necessary instructions, and I had the
satisfaction of knowing before I left the office that the cable, with its
good tidings, was on its way to America.
Then he sent for one of the naval men who had been interned there
since the beginning of the war and who was able to speak Dutch,
and told him to take good care of me.
After I had been bathed and shaved and had a hair-cut, I bought
some new clothes and had something to eat, and I felt like a new
man.
As I walked through the streets of Rotterdam, breathing the air of
freedom again and realizing that there was no longer any danger of
being captured and taken back to prison, it was a wonderful
sensation.
I don't believe there will ever be a country that will appear in my
eyes quite as good as Holland did then. I had to be somewhat
careful, however, because Holland was full of German spies, and I
knew they would be keen to learn all they possibly could about my
escape and my adventures, so that the authorities in Belgium could
mete out punishment to every one who was in any respect to blame
for it. As I was in Rotterdam only a day, they didn't have very much
opportunity to learn anything from me.
The naval officer who accompanied me and acted as interpreter for
me introduced me to many other soldiers and sailors who had
escaped from Belgium when the Germans took Antwerp, and as they
had arrived in Holland in uniform and under arms the laws of
neutrality compelled their internment, and they had been there ever
since.
The life of a man who is interned in a neutral country, I learned, is
anything but satisfactory. He gets one month a year to visit his
home. If he lives in England, that is not so bad, but if he happens to
live farther away, the time he has to spend with his folks is very
short, as the month's leave does not take into consideration the time
consumed in traveling to and from Holland.
The possibility of escape from internment is always there, but the
British authorities have an agreement with the Dutch government to
send refugees back immediately. In this respect, therefore, the
position of a man who is interned is worse than that of a prisoner
who, if he does succeed in making his escape, is naturally received
with open arms in his native land. Apart from this restraint, however,
internment, with all its drawbacks, is a thousand times—yes, a
million times better than being a prisoner of war in Germany.
It seems to me that when the war is over and the men who have
been imprisoned in Germany return home they should be given a
bigger and greater reception than the most victorious army that ever
marched into a city, for they will have suffered and gone through
more than the world will ever be able to understand.
No doubt you will find in the German prison-camps one or two faint-
hearted individuals with a pronounced yellow streak who voluntarily
gave up the struggle and gave up their liberty rather than risk their
lives or limbs. These sad cases, however, are, I am sure, extremely
few. Nine hundred and ninety-nine out of a thousand of the men
fighting in the Allied lines would rather be in the front-line trenches,
fighting every day, with all the horrors and all the risks, than be a
prisoner of war in Germany, for the men in France have a very keen
realization of what that means.
But to return to my day in Rotterdam.
After I was fixed up I returned to the consulate and arrangements
were made for my transportation to England at once. Fortunately
there was a boat leaving that very night, and I was allowed to take
passage on it.
Just as we were leaving Rotterdam the boat I was on rammed our
own convoy, one of the destroyers, and injured it so badly that it
had to put back to port. It would have been a strange climax to my
adventure if the disaster had resulted in the sinking of my boat and I
had lost my life while on my way to England after having
successfully outwitted the Huns. But my luck was with me to the
last, and while the accident resulted in some delay, our boat was not
seriously damaged and made the trip over in schedule time and
without further incident, another destroyer having been assigned to
escort us through the danger zone in place of the one which we had
put out of commission.
When I arrived in London the reaction from the strain I had been
under for nearly three months immediately became apparent. My
nerves were in such a state that it was absolutely impossible for me
to cross the street without being in deadly fear of being run over or
trampled on. I stood at the curb, like an old woman from the country
on her first visit to the city, and I would not venture across until
some knowing policeman, recognizing my condition, came to my
assistance and convoyed me across.
Indeed, there are a great number of English officers at home at all
times "getting back their nerve" after a long spell of active service at
the front, so that my condition was anything but novel to the London
bobbies.
It was not many days, however, before I regained control of myself
and felt in first-class shape.
Although the British authorities in Holland had wired my mother
from Holland that I was safe and on my way to England, the first
thing I did when we landed was to send her a cable myself.
The cable read as follows:
Mrs. M. J. O'Brien, Momence, Ill., U. S. A.:
Just escaped from Germany. Letter follows.
Pat.

As I delivered it to the cable-despatcher I could just imagine the


exultation with which my mother would receive it and the pride she
would feel as she exhibited it among her neighbors and friends.
I could hear the volley of "I told you so's" that greeted her good
tidings.
"It would take more than the Kaiser to keep Pat in Germany!" I
could hear one of them saying.
"Knew he'd be back for Christmas, anyway," I could hear another
remark.
"I had an idea that Pat and his comrades might spend Christmas in
Berlin," I could hear another admitting, "but I didn't think any other
part of Germany would appeal to him very much."
"Mrs. O'Brien, did Pat write you how many German prisoners he
brought back with him?" I could hear still another credulous friend
inquiring.
It was all very amusing and gratifying to me, and I must confess I
felt quite cocky as I walked into the War Department to report.
For the next five days I was kept very busy answering questions put
to me by the military authorities regarding what I had observed as
to conditions in Germany and behind the lines.
What I reported was taken down by a stenographer and made part
of the official records, but I did not give them my story in narrative
form. The information I was able to give was naturally of interest to
various branches of the service, and experts in every line of
government work took it in turns to question me. One morning
would be devoted, for instance, to answering questions of a military
nature—German methods behind the front-line trenches, tactics,
morale of troops, and similar matters. Then the aviation experts
would take a whack at me and discuss with me all I had observed of
German flying-corps methods and equipment. Then, again, the food
experts would interrogate me as to what I had learned of food
conditions in Germany, Luxembourg, and Belgium, and as I had lived
pretty close to the ground for the best part of seventy-two days I
was able to give them some fairly accurate reports as to actual
agricultural conditions, many of the things I told them probably
having more significance to them than they had to me.
There were many things I had observed which I have not referred to
in these pages because their value to us might be diminished if the
Germans knew we were aware of them, but they were all reported
to the authorities, and it was very gratifying to me to hear that the
experts considered some of them of the greatest value.
One of the most amusing incidents of my return occurred when I
called at my banker's in London to get my personal effects.
The practice in the Royal Flying Corps when a pilot is reported
missing is to have two of his comrades assigned to go through his
belongings, check them over, destroy anything that it might not be
to his interest to preserve, and send the whole business to his
banker or his home, as the case may be. Every letter is read
through, but its contents is never afterward discussed nor revealed
in any way. If the pilot is finally reported dead, his effects are
forwarded to his next of kin, but while he is officially only "missing"
or is known to be a prisoner of war they are kept either at the
squadron headquarters or sent to his banker's.
In my case, as soon as it was learned that I had fallen from the sky
it was assumed that I had been killed, and my chum, Paid Raney,
and another officer were detailed to check over my effects. The list
they made and to which they affixed their signatures, as I have
previously mentioned, is now in my possession and is one of the
most treasured souvenirs of my adventure.
My trunk was sent to Cox & Co. in due course, and now that I was in
London I thought I would go and claim it.
When I arrived in the bank I applied at the proper window for my
mail and trunk.
"Who are you?" I was asked, rather sharply.
"Well, I guess no one has any greater right to Pat O'Brien's effects
than I have," I replied, "and I would be obliged to you if you would
look them up for me."
"That may be all right, my friend," replied the clerk, "but according
to our records Lieutenant O'Brien is a prisoner of war in Germany,
and we can't very well turn over his effects to any one else unless
either you present proof that he is dead and that you are his lawful
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like