Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (4 votes)
9 views

[FREE PDF sample] (Ebook) MongoDB for Java developers design, build, and deliver efficient Java applications using the most advanced NoSQL database by Francesco, Marchioni ISBN 9781785280276, 9781785286292, 1785280279, 1785286293 ebooks

The document provides information on various ebooks available for download, including 'MongoDB for Java Developers' by Francesco Marchioni, which focuses on building efficient Java applications using MongoDB. It also lists additional recommended ebooks on topics like cooking, mathematics, and SAT preparation. The document includes links for downloading these ebooks and details about the authors and their expertise.

Uploaded by

galvexganjo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
9 views

[FREE PDF sample] (Ebook) MongoDB for Java developers design, build, and deliver efficient Java applications using the most advanced NoSQL database by Francesco, Marchioni ISBN 9781785280276, 9781785286292, 1785280279, 1785286293 ebooks

The document provides information on various ebooks available for download, including 'MongoDB for Java Developers' by Francesco Marchioni, which focuses on building efficient Java applications using MongoDB. It also lists additional recommended ebooks on topics like cooking, mathematics, and SAT preparation. The document includes links for downloading these ebooks and details about the authors and their expertise.

Uploaded by

galvexganjo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Visit https://ebooknice.

com to download the full version and


explore more ebooks

(Ebook) MongoDB for Java developers design, build,


and deliver efficient Java applications using the
most advanced NoSQL database by Francesco, Marchioni
ISBN 9781785280276, 9781785286292, 1785280279,
_____ Click the link below to download _____
1785286293
https://ebooknice.com/product/mongodb-for-java-
developers-design-build-and-deliver-efficient-java-
applications-using-the-most-advanced-nosql-
database-32704540

Explore and download more ebooks at ebooknice.com


Here are some recommended products that might interest you.
You can download now and explore!

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles, James


ISBN 9781459699816, 9781743365571, 9781925268492, 1459699815,
1743365578, 1925268497

https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena Alfredsson, Hans


Heikne, Sanna Bodemyr ISBN 9789127456600, 9127456609

https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT II Success)


by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018

ebooknice.com

(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master the SAT
Subject Test: Math Levels 1 & 2) by Arco ISBN 9780768923049,
0768923042

https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-
arco-master-the-sat-subject-test-math-levels-1-2-2326094

ebooknice.com
(Ebook) Cambridge IGCSE and O Level History Workbook 2C - Depth Study:
the United States, 1919-41 2nd Edition by Benjamin Harrison ISBN
9781398375147, 9781398375048, 1398375144, 1398375047

https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044

ebooknice.com

(Ebook) Refactoring in Java: Improving code design and maintainability


for Java developers by Stefano Violetta

https://ebooknice.com/product/refactoring-in-java-improving-code-
design-and-maintainability-for-java-developers-55039014

ebooknice.com

(Ebook) Java EE 7 Development with WildFly by Cmil, Michal, Matloka,


Michal, Marchioni, Francesco ISBN 9781782171980, 1782171983

https://ebooknice.com/product/java-ee-7-development-with-
wildfly-55591790

ebooknice.com

(Ebook) MongoDB Applied Design Patterns: Practical Use Cases with the
Leading NoSQL Database by Rick Copeland ISBN 9781449340049, 1449340040

https://ebooknice.com/product/mongodb-applied-design-patterns-
practical-use-cases-with-the-leading-nosql-database-55144854

ebooknice.com

(Ebook) Introducing Maven, 2nd Edition: A Build Tool for Today’s Java
Developers by Balaji Varanasi

https://ebooknice.com/product/introducing-maven-2nd-edition-a-build-
tool-for-todays-java-developers-50195460

ebooknice.com
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]
Chapter 1

Managing read-write concurrency


In RDBMS, managing the execution of concurrent work units is a fundamental
concept. The underlying implementation of each database uses behind the scenes
locks or Multiversion control to provide the isolation of each work unit. On the
other hand, MongoDB uses reader/writer locks that allow concurrent readers
shared access to a resource, such as a database or collection, but give exclusive
access to a single write operation. In more detail here is how MongoDB handles
read and write locks:

• There can be an unlimited number of simultaneous readers on a database


• There can only be one writer at a time on any collection in any one database
• The writers block out the readers once a write request comes in; all the
readers are blocked until the write completes (which is also known as
writer-greedy)

Since version 2.2 of MongoDB, it is possible to restrict the scope of the lock just the
database the read or write operation was working with. If you are using MongoDB
3.0 or later, the scope of the lock is pulled in further than ever before. Now, when a
write is occurring, only the documents involved in the write operation will be locked.
In order to store information about locks, MongoDB relies on a storage engine, which
is a part of the database and is responsible for managing how data is stored on the
disk. In particular, MongoDB 3.0 comes with two storage engines:

• MMAPv1: This is the default storage engine, which uses collection-level


locking
• WiredTiger: This is the new storage engine, which ships with document-
level locking and compression (only available for the 64-bit version)

By using the WiredTiger storage engine, all write operations happen


within the context of a document-level lock. As a result, multiple
clients can modify more than one document in a single collection
at the same time. Thanks to this granular concurrency control,
MongoDB can more effectively support workloads with read, write,
and updates, as well as high-throughput concurrent workloads.

[7]
Introduction to MongoDB

MongoDB core elements


In order to understand the capabilities of MongoDB, you need to learn the core
elements the database is composed of. Actually, MongoDB is organized with a
set of building blocks, which include the following:

• Database: This is, just like for the database, the top-level element. However,
a relational database contains (mostly) tables and views. A Mongo Database,
on the other hand, is a physical container of a structure called a collection.
Each database has its own set of files on the filesystem. A single MongoDB
server typically has multiple databases.
• Collection: This is a set of MongoDB documents. A collection is the
equivalent of an RDBMS table. There can be only one collection with that
name on the database but obviously multiple collections can coexist in a
database. Typically, the collections contained in a database are related,
although they do not enforce a schema as RDBMS tables do.
• Documents: This is the most basic unit of data in MongoDB. Basically, it is
composed by a set of key-value pairs. Unlike database records, documents
have a dynamic schema, which means documents that are part of the same
collection do not need to have the same set of fields. Much the same way,
the fields contained in a document may hold different data types.

The following diagram summarizes the concepts we just discussed:

[8]
Chapter 1

The heart of MongoDB – the document


At the heart of MongoDB is the document, an ordered set of keys with associated
values. The representation of a document varies by the programming language,
but most languages have a data structure that is a natural fit, such as a map, hash,
or dictionary. Here is a very basic example of a document, which is understood
by MongoDB:
{"name" : "Francesco",
"age" : 44,
"phone":"123-567-890"}

Most documents will be more complex than this simple one and will often contain
embedded data within them. These denormalized data models allow applications
to retrieve and manipulate related data in a single database operation:
{"name" : "Francesco",
"age" : 44,
"contact" : {
"phone":"123-567-890"
}
}

As you can see from the preceding example, we have included the contact information
within the same document by using an embedded document with a single key
named contact.

Each document requires a key, which needs to be unique within a document. The keys
contained in a document are strings. Any UTF-8 character can be included in a key,
with a few exceptions:

• You cannot include the character \0 (also known as the null character) in a
key. This character is used to indicate the end of a key.
• The . and $ characters are internally used by the database so they should be
used only in limited cases. As a general rule, it is better to completely avoid
using these characters as most MongoDB drivers can generate exceptions
when they are used inappropriately.

Finally, you need to be aware that MongoDB is both type-sensitive and case-
sensitive. For example, these documents are distinct:
{"age" : 18}
{"age" : "18"}

[9]
Introduction to MongoDB

The same applies to the following documents:


{"age" : 18}
{"Age" : 18}

Understanding how MongoDB stores data


The sample documents you have seen so far should be familiar to you if you
have ever heard about JavaScript Object Notation (JSON). JSON is a human and
machine-readable open standard that simplifies data interchange and is also one of
the most used formats for data interchange in applications along with XML. JSON
is able to deal with all the basic data types used by applications such as String,
numbers, Boolean values, as well as arrays and hashes. MongoDB is able to store
JSON documents into its collections to store records. Let's see an example of a
JSON document:
{
_id":1,
"name":{
"first":"Dennis",
"last":"Ritchie"
},
"contribs":[
"Altran",
"B",
"C",
"Unix"
],
"awards":[
{
"award":"Turing Award",
"year":1983
},
{
"award":"National medal of technology",
"year":1999
}
]
}

A JSON-based database returns a set of data that can be easily parsed by most
programming languages such as Java, Python, JavaScript, and others, reducing
the amount of code you need to build into your application layer.

[ 10 ]
Chapter 1

Behind the scenes, MongoDB represents JSON documents using a binary-encoded


format called BSON. Documents encoded with BSON enhance the JSON data model
to provide additional data types and efficiency when encoding/decoding data
within different languages.

MongoDB uses a fast and lightweight BSON implementation, which is highly


traversable and supports complex structures such as embedded objects and arrays.

Data types accepted in documents


So far, we have used just two basic data types, String and Integer. MongoDB offers a
wide choice of data types, which can be used in your documents:

• String: This is the most common data type as it contains a string of text
(such as: "name": "John").
• Integer (32 bit and 64-bit): This type is used to store a numerical value
(for example, "age" : 40). Note that an Integer requires no quotes
to be placed before or after the Integer.
• Boolean: This data type can be used to store either a TRUE or a FALSE value.
• Double: This data type is used to store floating-point values.
• Min/Max keys: This data type is used to compare a value against the lowest
and highest BSON elements, respectively.
• Arrays: This type is used to store arrays or list or multiple values into one
key (for example, ["John, Smith","Mark, Spencer"]).
• Timestamp: This data type is used to store a timestamp. This can be useful
to store when a document has been last modified or created.
• Object: This data type is used for storing embedded documents.
• Null: This data type is used for a null value.
• Symbol: This data type allows storing characters such as String; however,
it's generally used by languages that use a specific symbol type.
• Date: This data type allows storing the current date or time in the Unix time
format (POSIX time).
• Object ID: This data type is used to store the document's ID.
• Binary data: This data type is used to store a binary set of data.
• Regular expression: This data type is used for regular expressions. All options
are represented by specific characters provided in alphabetical order. You will
learn more about regular expressions.
• JavaScript code: This data type is used for JavaScript code.

[ 11 ]
Introduction to MongoDB

Installing and starting MongoDB


Installing Mongo DB is much easier than most RDBMS as it's just a matter of
unzipping the archived database and, if necessary, configure a new path for data
storage. Let's look at the installation for different operating system architectures.

Installing MongoDB on Windows


For installing MongoDB on Windows, perform the following steps:

1. Download the latest stable release of MongoDB from http://www.mongodb.


org/downloads. (At the time of writing, the latest stable release is 3.0.3, which
is available as Microsoft Installer or as a ZIP file). Ensure you download the
correct version of MongoDB for your Windows system.
2. Execute the MSI Installer, or if you have downloaded MongoDB as a ZIP file,
simply extract the downloaded file to C:\drive or any other location.

MongoDB requires a data directory to store its files. The default location for the
MongoDB data folder on Windows is c:\data\db. Execute the following command
from the command prompt to create the default folder:
C:\mongodb-win32-x86_64-3.0.3>md data

In Command Prompt, navigate to the bin directory present in the mongodb


installation folder and point to the folder where data is stored:
C:\mongodb-win32-x86_64-3.0.3\bin> mongod.exe --dbpath "C:\mongodb-
win32-x86_64-3.0.3\data"

This will show the waiting for the connections message on the console output,
which indicates that the mongod.exe process is running successfully.

[ 12 ]
Chapter 1

Installing MongoDB on Linux


The installation on Linux can be different depending on your Linux distribution.
Here is a general-purpose installation process:

1. Download the latest MongoDB distribution, which is appropriate for your


OS architecture:
curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-
3.0.3.tgz

2. Extract the downloaded files:


tar -zxvf mongodb-linux-x86_64-3.0.3.tgz

3. Copy files to a target directory:


mkdir -p mongodb
cp -R -n mongodb-linux-x86_64-3.0.3/ mongodb

4. Include MongoDB scripts in the system's PATH variable:


export PATH=<mongodb-install-directory>/bin:$PATH

5. Just like we did for Windows, we will create the data folder:
mkdir -p /data/db

6. Now, you can start MongoDB much the same way as with Windows:
mongod --dbpath /data/db

[ 13 ]
Introduction to MongoDB

MongoDB start up options


The list of start up options, which can be applied to the mongod server is quite
large and is detailed at http://docs.mongodb.org/manual/reference/program/
mongod/.

The following table summarizes the most common options for a handy reference:

Option Description
--help, -h This returns the information on the options and use of
mongod.
--version This returns the mongod release number.
--config <filename> This specifies the configuration file to be used by
mongod.
--port <port> This specifies the TCP listening port on which
MongoDB listens. (the default is 27017)
--bind_ip <ip address> This specifies the IP address that mongod binds to in
order to listen for connections from applications (the
default is All interfaces.).
--logpath <path> This sends all diagnostic logging information to a log
file instead of to a standard output or to the host's
syslog system.
--logappend This appends new entries to the end of the log file
rather than overwriting the content of the log when the
mongod instance restarts.
--httpinterface This enables the HTTP interface. Enabling the interface
can increase network exposure.
--fork This enables a daemon mode that runs the mongod
process in the background. By default, mongod does
not run as a daemon.
--auth This enables authorization to control the user's
access to database resources and operations. When
authorization is enabled, MongoDB requires all clients
to authenticate themselves first in order to determine
the access for the client.
--noauth This disables authentication. It is currently the default
and exists for future compatibility and clarity.
--rest This enables the simple REST API. Enabling the REST
API enables the HTTP interface, even if the HTTP
interface option is disabled, and as a result can increase
network exposure.

[ 14 ]
Chapter 1

Option Description
--profile <level> This changes the level of database profiling (0 Off,
which means no profiling; 1 On, which only includes
slow operations; and 2 On, which includes all the
operations.)
--shutdown This safely terminates the mongod process. It is
available only on Linux systems.

In addition, the following options can be used to vary the storage of the database:

Option Description
--dbpath <path> This is the directory where the mongod instance stores
its data. The default is /data/db on Linux and OS X
and C:\data\db on Windows.
--storageEngine string This specifies the storage engine for the mongod
database. The valid options include mmapv1 and
wiredTiger. The default is mmapv1.
--directoryperdb This stores each database's files in its own folder in the
data directory. When applied to an existing system,
the --directoryperdb option alters the storage
pattern of the data directory.

Troubleshooting MongoDB installation


On startup, the server will print some version and system information and then
begin waiting for connections. By default, MongoDB listens for connections on port
27017. The server process will fail to start if the port is already used by another
process—the most common cause of it is that another instance of MongoDB is
already running on your machine.

You can stop mongod by typing Ctrl + C in the shell that is


running the server. In a clean shutdown, the mongod process
completes all running operations, flushes all data to files, and
closes all data files. Within the Securing database access section
of this chapter, we show how to use the Mongo shell to shut
down the database from the Mongo shell.

[ 15 ]
Introduction to MongoDB

The mongod command also launches a basic HTTP server that listens,
by default, on port 28017. This web server can be used to capture REST request
(see http://docs.mongodb.org/ecosystem/tools/http-interfaces/) and
to query for administrative information about your database by pointing to
http://localhost:28017 with your web browser.

You need to start mongod with the --rest option in order


to enable the web administration console.

The following screenshot depicts the web administration GUI when executed from
the browser:

Mongo tools
MongoDB ships with a set of shell commands, which can be useful to administrate
your server. We will shortly provide a description of each command, so that you can
get an initial introduction to the server administration:

• bsondump: This displays BSON files in a human-readable format


• mongoimport: This converts data from JSON, TSV, or CSV and stores them
into a collection

[ 16 ]
Chapter 1

• mongoexport: This writes an existing collection using the CSV or JSON formats
• mongodump/mongorestore: This dumps MongoDB data to disk using the
BSON format (mongodump), or restores them (mongorestore) to a live database
• mongostat: This monitors running MongoDB servers, replica sets, or clusters
• mongofiles: This reads, writes, deletes, or updates files in GridFS
• mongooplog: This replays oplog entries between MongoDB servers
• mongotop: This monitors data reading/writing on a running Mongo server

Here is an example of how to use the mongoimport tool to import a CSV-formatted


data contained in /var/data/users.csv into the collection users in the sample
database on the MongoDB instance running on the localhost port numbered 27017:
mongoimport --db sample --collection users --type csv --headerline --file
/var/data/users.csv

In the preceding example, mongoimport determines the name of files using the first
line in the CSV file, because of --headerline.

If you want to export the MongoDB documents, you can use the mongoexport tool.
Let's look at an example of how to export the collection users (part of the sampled
database), limited to the first 100 records:
mongoexport --db sampledb --collection users --limit 100 --out export.
json

As part of your daily backup strategy, you should consider using the mongodump
tool, which is a utility for creating a binary export of the contents of a database.

mongodump does not provide a backup of the local database.

The following command creates a database dump for the collection named users
contained in the database named sampled. In this case, the database is running on
the local interface on port 27017:
mongodump --db test --collection users

The preceding command will create a BSON binary file named users.bson and a
JSON file named users.metadata.json containing the documents. The files will be
created under dump/[database-name].

[ 17 ]
Introduction to MongoDB

Finally, the mongorestore program loads binary data from a database dump
created by mongodump to a MongoDB instance. mongorestore can both create a new
database and add data to an existing database:
mongorestore --collection users --db sampledb dump/sampledb/users.bson

Introduction to the MongoDB shell


MongoDB ships with a JavaScript shell that allows interaction with a MongoDB
instance from the command line. The shell is the bread-and-butter tool for
performing administrative functions, monitoring a running instance, or just inserting
documents.

To start the shell, run the mongo executable:


$ mongo
MongoDB shell version: 3.0.3
connecting to: test

The shell automatically attempts to connect to a running MongoDB server on


startup, so make sure you start mongod before starting the shell.

If no other database is specified on startup, the shell selects a default database called
test. As a way of keeping all the subsequent tutorial exercises under the same
namespace, let's start by switching to the sampledb database:
> use sampledb
switched to db sampledb

If you are coming from an RDBMS background, you might be surprised that we can
switch to a new database without formerly creating it. The point is that creating the
database is not required in MongoDB. Databases and collections are first created
when documents are actually inserted. Hence, individual collections and databases
can be created at runtime just as the structure of a document is known.

If you want to check the list of available databases, then you can use the show dbs
command:
>show dbs
local 0.78125GB
test 0.23012GB

As you can see, the database we created (sampledb) is not present in the list. To
display the database, you need to insert at least one document into it. The next
section will show you how to do it.

[ 18 ]
Chapter 1

Inserting documents
As we said, MongoDB documents can be specified in the JSON format. For example,
let's recall the simple document that we have already introduced:
{"name" : "francesco",
"age" : 44,
"phone":"123-567-890"
}

In order to insert this document, you need to choose a collection where the document
will be stored. Here's how you can do it with the Mongo shell:
db.users.insert({"name": "francesco","age": 44, "phone": "123-567-
890"})

As for databases, collections can be created dynamically by specifying it into the


insert statement. Congratulations, you've just saved your first document!

MongoDB supports a special kind of collection named Capped


collections, which are fixed-size collections that are able to support
high-throughput operations where insert and retrieve documents
are based on insertion order. Capped collections need to be created
first before being able to use them. We will show you how to use
Capped collections in the next chapter, using the Java driver.

Querying documents
The find method is used to perform queries in MongoDB. If no argument is given to
the find method, it will return all the documents contained in the collection as in the
following statement:
> db.users.find()

The response will look something like this:


{ "_id" : ObjectId("5506d5988d7bd8471669e675"), "name" : "francesco",
"age" : 44, "phone" : "123-456-789" }

Maybe you have noticed that the _id field has been added to the document. This
is a special key that works like a primary key. As a matter of fact, every MongoDB
document requires a unique identifier and if you don't provide one in your
document, then a special MongoDB ID will be generated and added to the document
at that time.

[ 19 ]
Introduction to MongoDB

Now, let's include another user in our collections so that we can refine our searches:
> db.users.insert({"name": "owen","age": 32, "phone": "555-444-333"})

Your collection should now include two documents, as verified by the count function:
> db.users.count()
2

As you can see from the preceding insert command, document


keys are specified with quotes. This is not mandatory but generally
a good practice as it makes queries more readable.

Having two documents in our collection, we will learn how to add a query selector
to our find statement so that we filter users based on a key value. For example, here
is how to find a user whose name is owen:
> db.users.find({"name": "owen"})
{ "_id" : ObjectId("5506eea18d7bd8471669e676"), "name" : "owen",
"age" : 32, "phone" : "555-444-333" }

Multiple conditions can be specified within a query, just like you would do with a
WHERE – AND construct in SQL:

> db.users.find({"name": "owen", "age": 32})

{ "_id" : ObjectId("5506eea18d7bd8471669e676"), "name" : "owen",


"age" : 32, "phone" : "555-444-333" }

Choosing the keys to return


The queries mentioned earlier are equivalent to a SELECT * statement in SQL terms.
You can use a projection to select a subset of fields to return from each document
in a query result set. This can be especially useful when you are selecting large
documents, as it will reduce the costs of network latency and deserialization.

Projections are commonly activated by means of binary operators (0,1); the binary
operator 0 means that the key must not be included in the search whilst 1 obviously
means that the key has to be included. Here is an example of how to include the name
and age keys in the fields to be returned (along with the id field, which is always
included by default:
> db.users.find({}, {"name": 1,"age": 1})

[ 20 ]
Chapter 1

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


"age" : 44 }
{ "_id" : ObjectId("5506eea18d7bd8471669e676"), "name" : "owen", "age" :
32 }

By setting the projection values for the name and age to 0, the phone number is
returned instead:
> db.users.find({}, {"name": 0,"age": 0})
{ "_id" : ObjectId("5506d5988d7bd8471669e675"), "phone" : "123-456-789" }
{ "_id" : ObjectId("5506eea18d7bd8471669e676"), "phone" : "555-444-333" }

Note that you cannot have a mix of inclusions and exclusions


in your projection. The exception to the rule is the _id field. In
fact, {_id: 0, name: 1, age: 1} works but any inclusion/
exclusion combination of other fields does not.

Using ranges in your queries


Quite commonly, your queries will use some functions to restrict the range of the
returned data, which is done in most SQL dialects and languages with the > and <
or = operators.

The equivalent operators in MongoDB terms are $gt, $gte, $lt, and $lte. Here is
how to find users whose age is greater than 40 using the $gt operator:
> db.users.find({ age: { $gt: 40 } })

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


"age" : 44, "phone" : "123-456-789" }

The $gte operator, on the other hand, is able to select keys that are greater than or
equal (>=) to the one specified:
> db.users.find({ age: { $gte: 32 } })

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


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

The $lt and $lte operators, on the other hand, allow you to select keys which are
smaller and smaller/equal to the value specified.

[ 21 ]
Introduction to MongoDB

Using logical operators to query data


You cannot think of a scripting language without logical operators and MongoDB
is no exception. The most common logical operators are named $or, $and, and $not
in MongoDB.

We will not enter into the basics of logical operators, rather let's see a concrete
example of the logical operator OR:
db.users.find( { $or: [ { "age": { $lt: 35 } }, { "name": "john" } ]
} )

In the preceding query, we are selecting users whose age is smaller than 35 or have
the name john. As one of the conditions evaluates to true, it will return one user:
{ "_id" : ObjectId("5506eea18d7bd8471669e676"), "name" : "owen",
"age" : 32, "phone" : "555-444-333" }

By turning to the AND logical operator, on the other hand, no users will be returned:
db.users.find( { $and: [ { "age": { $lt: 35 } }, { "name": "john" } ] } )

By using the NOT operator, you can invert the effect of a query expression and
return documents that do not match the query expression. For example, if you
wanted to query for all users with last names not beginning with f, you could
use $not as follows:
> db.users.find({"name": {$not: /^f/} })
{ "_id" : ObjectId("5506eea18d7bd8471669e676"), "name" : "owen", "age" :
32, "phone" : "555-444-333" }

Using LIKE in Mongo


Note the /expr/ operator, which can be used to achieve a SQL-
like equivalent expression. For example, in its simplest form, you
can use it to query for phone numbers, which are like 444:
> db.users.find({"phone": /444/})

Updating documents
In order to update an existing document, you need to provide two arguments:

• The document to update


• How the selected documents should be modified

[ 22 ]
Chapter 1

Let's see a practical example, supposing that you wanted to change the key age for
the user owen to be 39:
> db.users.update({name: "owen"}, {$set: {"age": 39}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

The outcome of the statement informs us that the update matched one document
which was modified. A find issued on the users collection reveals that the change
has been applied:
> db.users.find()

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


"age" : 44, "phone" : "123-456-789" }
{ "_id" : ObjectId("5506eea18d7bd8471669e676"), "name" : "owen", "age" :
39, "phone" : "555-444-333" }

Be aware that executing an update without the $set operator


won't update the fields but replace the whole document, while
preserving the _id field.

The update supports an additional option, which can be used to perform a more
complex logic. For example, what if you wanted to update the record if it exists, and
create it if it doesn't? This is called upsert and can be achieved by setting the upsert
option to true, as in the following command line:
> db.users.update({user: "frank"}, {age: 40},{ upsert: true} )

WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("55082f5ea30be312eb167fcb")
})

As you can see from the output, an upsert has been executed and a document with
the age key has been added:
> db.users.find()

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


"age" : 44, "phone" : "123-456-789" }

[ 23 ]
Introduction to MongoDB

{ "_id" : ObjectId("5506eea18d7bd8471669e676"), "name" : "owen", "age" :


39, "phone" : "555-444-333" }
{ "_id" : ObjectId("55082f5ea30be312eb167fcb"), "age" : 40 }

Updating a document with MongoDB can be done also on a portion of a document,


for example, you can remove a single key from your collection by using the $unset
option. In the following update, we are removing the age key to all documents
whose name key equals to owen.
> db.users.update({name: "owen"}, {$unset : { "age" : 1} })

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Executing the find on our collection confirms the update:


> db.users.find()

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


"age" : 44, "phone" : "123-456-789" }
{ "_id" : ObjectId("5506eea18d7bd8471669e676"), "name" : "owen", "phone"
: "555-444-333" }
{ "_id" : ObjectId("55082f5ea30be312eb167fcb"), "age" : 40 }

The opposite of the $unset operator is $push, which allows you to append a value to
a specified field. So here is how you can restore the age key for the user owen:
> db.users.update({name: "owen"}, {$push : { "age" : 39} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

You can achieve the same result by using $set on a field,


which is not included in the document.

Deleting data
As you have just seen, the update operator is quite flexible and allows trimming
or pushing keys to your collections. If you need to delete a whole set of documents,
then you can use the remove operator. When used without any parameter, it is
equivalent to the TRUNCATE command in SQL terms:
> db.users.remove()

[ 24 ]
Chapter 1

Most of the time, you need to be more selective when deleting documents as you
might need to remove just a set of documents matching one or more conditions.
For example, here is how to remove users older than 40:
> db.users.remove({ "age": { $gt: 40 } })
WriteResult({ "nRemoved" : 1 })

Just like the TRUNCATE statement in SQL, it just removes documents from a
collection. If you want to delete the collection, then you need to use the drop()
method, which deletes the whole collection structure, including any associated index:
> db.users.drop()

Beyond basic data types


Although the basic data types we have used so far will be fine for most use cases,
there are a couple of additional types that are crucial to most applications, especially
when mapping Mongo types to a language driver such as a Mongo driver for Java.

Arrays
MongoDB has a rich query language that supports storing and accessing documents
as arrays. One of the great things about arrays in documents is that MongoDB
understands their structure and knows how to reach inside arrays to perform
operations on their content. This allows us to query on arrays and build indexes
using their content.

Let's start creating a couple of documents containing an array of items:


> db.restaurant.insert({"menu" : ["bread", "pizza", "coke"]})
WriteResult({ "nInserted" : 1 })

> db.restaurant.insert({"menu" : ["bread", "omelette", "sprite"]})

WriteResult({ "nInserted" : 1 })

We will now show you how to query on the array selection to find the menu,
which includes pizza:
> db.restaurant.find({"menu" : "pizza"})

{ "_id" : ObjectId("550abbfe89ef057ee0671650"), "menu" : [


"bread","pizza", "coke" ] }

[ 25 ]
Introduction to MongoDB

Should you need to match arrays using more than one element, then you can use
$all. This allows you to match a list of elements. For example, let's see how you can
query on the above collection by matching two items in the menu:
> db.restaurant.find({"menu" : {$all : ["pizza", "coke"]}})

{ "_id" : ObjectId("550abbfe89ef057ee0671650"), "menu" : [ "bread",


"pizza", "coke" ] }

Embedded documents
You can use a document as a value for a key. This is called an embedded document.
Embedded documents can be used to organize data in a more natural way than
just a flat structure of key-value pairs. This matches well with most object-oriented
languages, which holds a reference to another structure in their class.

Let's start by defining a structure, which is assigned to a variable in the mongo shell:
x = {
"_id":1234,
"owner":"Frank's Car",
"cars":[
{
"year":2011,
"model":"Ferrari",
price:250000
},
{
"year":2013,
"model":"Porsche",
price:250000
}
]
}

Since the Mongo shell is a JavaScript interface, it is perfectly fine to write something
like the preceding code and even use functions in order to enhance objects in the shell.
Having defined our variable, we can insert it into the cars collection as follows:
> db.cars.insert(x);
WriteResult({ "nInserted" : 1 })

[ 26 ]
Chapter 1

Alright. We have just inserted a document which in turn contains an array


of documents. We can query our subdocument by using the dot notation.
For example, we can choose the list of cars whose model is Ferrari by
using the cars.model criteria:
> db.cars.find( { "cars.model": "Ferrari" }).pretty()
{
"_id" : 1234,
"owner" : "Frank's Car",
"cars" : [
{
"year" : 2011,
"model" : "Ferrari",
"price" : 250000
},
{
"year" : 2013,
"model" : "Porsche",
"price" : 250000
}
]

Also, the pretty function provides a pretty formatted


JSON in the response.

Some useful functions


We will complete our excursus on the Mongo shell with some handy functions,
which can be used to achieve a more precise control over your queries. The ones
we will cover in this section are the limit, sort, and skip functions.

You can use the limit function to specify the maximum number of documents
returned by your query. You obviously need to provide the number of records to
be returned as a parameter. By setting this parameter to 0, all the documents will
be returned:
> db.users.find().limit(10)

[ 27 ]
Introduction to MongoDB

The sort function, on the other hand, can be used to sort the results returned from
the query in ascending (1) or descending (-1) order. This function is pretty much
equivalent to the ORDER BY statement in SQL. Here is a basic example of sort:
> 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" }

This example sorts the results based on the name key-value in ascending order,
which is the default sorting order. If you want to switch to the descending order,
then you would need to add the -1 flag to the sort operator.

Note that the sort function when issued against the document's
_id will be sorted on a time criteria.

The next one in the list is the skip function, which skips the first n documents in a
collection. For example, here is how to skip the first document in a search across the
users collection:

> db.users.find().skip(1)
{ "_id" : ObjectId("550ad3ef89ef057ee0671652"), "name" : "owen", "age" :
32, "phone" : "555-444-333" }

All the preceding commands can be also combined to produce a powerful


expression. For example, the preceding command will return a different user
when combined with a sort function in descending order:
> db.users.find().skip(1).sort({"name":-1})
{ "_id" : ObjectId("5506d5708d7bd8471669e674"), "name" : "francesco",
"age" : 44, "phone" : "123-456-789" }

Securing database access


We will conclude this chapter by informing you about database security. So far,
we have started and used MongoDB without any authentication process. Actually,
starting mongod without any additional option exposes the database to any user
who is aware of the process.

[ 28 ]
Chapter 1

We will show how to provide secure access by means of the mongo shell. So, launch
the mongo shell and connect to the admin database, which holds information about
the users:
use admin

Now, let's use the createUser function to add a user named administrator with
the password mypassword and grant unlimited privileges (the role root):
db.createUser(
{
user: "administrator",
pwd: "mypassword",
roles: [ "root" ]
}
)

Now, shut down the server by using the following command:


db.shutdownServer()

We will restart the database using the –-auth option, which forces user
authentication:
mongod --dbpath "C:\mongodb-win32-x86_64-3.0.3\data" --auth

Now, the database is started in secure mode. You can connect from the mongo shell
in two different ways. The first one should be used with caution on Linux/Unix
systems, as it exposes the user/password in the process list:
mongo -u administrator -p mypassword --authenticationDatabase admin

As an alternative, you can start the mongo shell and authenticate it at the beginning
of the session (you need to select the admin database at first as the authentication
keys are stored on the admin DB):
use admin
db.auth('admin','mypassword')

use yourdb
. . . .

[ 29 ]
Introduction to MongoDB

Summary
This chapter has provided a whistle-stop tour of the basics of the MongoDB and
NoSQL databases. We have gone through some advantages that can be gained when
choosing a NoSQL database and the trade-offs compared with a relational database.

Then, we took you through the installation of MongoDB and some start up options
that can be used to customize your server. Finally, we talked about the MongoDB
shell and learned how to manipulate data using some basic CRUD operations.

In the next chapter, we will show you how to connect to MongoDB using the Java
driver and perform some equivalent actions using Java.

[ 30 ]
Chapter 2

Getting Started with Java


Driver for MongoDB
This chapter discusses the MongoDB Java interface that consists of a JDBC driver
that needs to be downloaded and included in your application's classpath. By using
the MongoDB Java driver, you will be able to perform all the create/read/update/
delete (CRUD) operations that we have so far accomplished using the mongo shell.
The list of topics covered includes the following:

• Downloading and installing the MongoDB JDBC driver


• Setting up a basic Java project using Eclipse
• Performing common CRUD operations using a Java application

Getting the Mongo JDBC driver


The MongoDB Java driver can be downloaded from the Maven central repository at
http://central.maven.org/maven2/org/mongodb/mongo-java-driver/. Make
sure you download the latest stable release of it.

At the time of writing, version 3.0.0 of the MongoDB Java driver has
just been released. The new version of the driver deprecates some of
the core interfaces available in version 2.X, which is still the de facto
standard in Java projects using MongoDB. For this reason, we will start
with the latest stable 2.X version, showing the new driver in action in
the Using the MongoDB Java driver version 3 section.

[ 31 ]
Exploring the Variety of Random
Documents with Different Content
In what remained of the church, cots had been set up for the
wounded, and here doctors and Red Cross nurses were busy.
As they stopped in front of this place a voice shrilled out: “But I tell
you, monsieur, I am neither ill nor insane. It is as I say and I must
be gone at once. You must not detain me.”
Lucie gave a start. “Listen!” she cried.
“I appeal to you, madame,” the voice went on. “Figure to yourself a
daughter of yours, alone, stricken with terror, not knowing where to
go, feeling herself utterly deserted. It is of all things impossible that
I should be detained. Bah, what is a cut on the head? A nothing.
Yes, to be sure I was insensible, but at this moment I have my
faculties, and I am so weak that I cannot make that little journey.
You will send? But the child in that foul cow shed all night! Who
knows if she be not ill or has left the place and is wandering about
lost and forsaken?”
“Paulette!” cried Lucie darting up the steps of the battered church,
from which came the voice. “Paulette, are you then here? It is I,
Lucie.”
From the doorway, which was scarce more than a gaping hole
rushed forth a stout figure with bandaged head and torn clothing.
“My little one! The blessed child! It is she herself,” cried Paulette
grasping Lucie by the hands and drawing her inside. “Monsieur the
doctor, Madame the nurse, behold the child. She is here. Is it not a
miracle of le bon Dieu?” Paulette, excited, half laughing, half crying,
held tightly to Lucie.
The doctor and nurse stood by smiling appreciatively. “Tell us how
you managed to get here safely, mademoiselle,” said the doctor.
So Lucie told her tale which was interrupted by many exclamations
from Paulette, but was listened to with interest by all who heard.
“Surely the saints had you in keeping,” said Paulette, when the story
was ended. “For there is danger everywhere and in coming here you
might have been killed as I nearly was.”
“Tell me of that,” urged Lucie. “Were you badly hurt, Paulette? Are
you suffering, my poor one?”
“Not now so much. It was this way that it happened, ma petite: I
was coming into the town. I had arrived as you may say. Suddenly a
great noise, a crash. I knew no more till I find myself within these
walls, if walls one can still call them. I am at first unable to collect
my thoughts. At last I realize that here am I with a hole in the head
and so weak that when I stand I am afflicted with a dizziness. I wish
to go to you, but no, this is impossible. I try to explain. This, too, is
difficult. It is then the middle of the night, I know not what hour. I
lie down again and sleep, perhaps. When I awake I am given food. I
am better, and then I begin to implore that I be allowed to return to
you. These, though good and kind, refuse to permit me to go. Tell
me, little one, how did you fare in that so unclean place? You, of
course had food from the basket.”
“But no, Paulette, for alas, it was the wrong basket. The one in
which was the food, that went with grandfather.”
“Mon Dieu!” exclaimed Paulette. “How I am a stupid? What a sot
animal, a dindon I am not to have perceived that, and then I had
not this wound upon the head which would have given me some
excuse for stupidity.”
“But you realize, Paulette, that those two baskets were exactly alike.”
“That matters nothing, for the fact remains that you were without
food. Monsieur, Madame, she starves, this child. She has eaten
nothing since noon yesterday.”
“Oh yes, but I have,” Lucie hastened to assure her. “You will scarce
believe what I have to tell you, and will say it is nothing short of a
miracle indeed.” And she proceeded to tell of Pom Pom’s
achievement to a still more interested audience.
“This dog, this very clever creature, where is he?” asked the doctor
when she had ended her recital.
“He is here,” Lucie told him waving her hand to where, on outside,
Pom Pom was quite content to wait with Victor.
“We must see this so clever animal,” declared the doctor, going to
the foot of the steps where Victor was sitting.
“And my grandfather?” said Lucie turning again to Paulette. “He is
safe? He is here?”
“He is safe, let us hope. None were allowed to remain when the
authorities evacuated the town. All were forced to leave. To be sure,
I hear there were some who hid themselves and would not go. This
Paulette, that you see, she stayed because perforce she must. It is
perhaps a Providence which sent that blow upon the head or out I
must have gone whether I would or not, and then what would have
become of you?”
“There was Victor,” said Lucie thoughtfully.
“Oh, yes, Victor. La la, there was Victor,” exclaimed Paulette
marching off. Lucie could not tell whether offended or not.
But presently she returned with the nurse whom Lucie had first seen
and who brought a bowl of soup which Lucie received gratefully, and
which she felt inclined to eat to the very last drop for it was hot and
comforting. But she left a few spoonfuls saying to the nurse, “I may
give this to Pom Pom?”
“Eat it all, my dear,” replied the nurse smiling. “We can find
something else for a little dog who is so faithful.”
Pom Pom provided for, the next thing was to consult Victor about
various matters. There were the things left in the cow shed which
Paulette declared she could not live without. How were they to
recover these? and where would they be liable to find Mons. Du
Bois? Lucie put these questions anxiously.
Victor thus appealed to felt himself more than ever thrust into the
rôle of protector and gave up then and there his last hope of getting
home on this furlough. He could not desert Lucie. It would never do
to start her out upon a journey with Paulette who was in no
condition to travel on foot, and there did not appear any one to
whose care he might intrust a young girl and a wounded woman. He
pondered over the situation, Lucie watching him anxiously.
“Listen,” he said at last, smiling down at the troubled girl, his kind
brown eyes alight with sympathy, “I think we can work our way out
of this difficulty. Trust it all to me. At present you are quite safe here.
I will go back for those things, if needs be, but first I will inquire
about this lost grandfather who, no doubt, is as concerned about
you as you about him. I will see if I can discover something of him.
Let us see, he was traveling in a wagon with one you know. Is this
right?”
“Yes, he was with Gustave Foucher, a tradesman in our town and
whom we all know well as a kind, good man. Gustave has his family
with him, and some household goods, yet he was willing to take
grandfather, too. The wagon is drawn by two stout black horses.”
“Good, we will then see what we can learn of this Gustave Foucher,
and then I will report to you, then it will be time enough to attend to
those baskets in the cow shed.”
“Oh, Victor, how good you are,” cried Lucie, gratefully.
“La la, who is good? Not any one really. I do this because it amuses,
it entertains; it is out of the day’s routine, an adventure, as one
might say. Pom Pom had better stay with you while I pursue my
investigations.”
He went off to follow up his course of action, leaving Lucie to
reënter the church where Paulette was busying herself in waiting on
those more helpless than herself. It was a gruesome place, Lucie
thought, with its row of cots in which lay groaning sufferers, some
too severely hurt to hope for recovery, and some who would never
again be whole. This was war, her first intimate acquaintance with its
horrors. In such a place perhaps her father lay at this moment. She
prayed that he might be spared and that her mother was at his side,
as she knelt for a moment before an untouched altar. When she
arose to her feet she saw Paulette trying to make more comfortable
a patient close by.
“Can’t I help, too?” whispered Lucie.
Paulette shook her head, but one of the nurses beckoned to her and
she followed her to the sacristy where a sort of kitchen was
established. “I wouldn’t stay in there,” said the nurse. “Perhaps you
can help here. You can, maybe, wash dishes.”
“Oh, I can do that,” Lucie assured her and diligently set to work,
feeling thankful that something useful was her part to perform.
She was not long at her occupation, however, for before she had
quite finished the pile before her, Victor came back.
“Your friend, the young man, has returned,” some one came to tell
her.
Lucie looked inquiringly at the young woman who was in charge.
She nodded encouragingly. “Go, my dear. You have been very
helpful,” said the woman.
She gave up the towel she had been using and went softly out,
tiptoeing past the row of cots. Victor was waiting on the steps.
“What news?” inquired Lucie.
“All’s well,” he answered. “That grandfather has been through here.
He left word with the man who has been station master but who no
more is so because there is no station. With this person he has left
word that he is not allowed to stop and is going on to the next point
where one can get a train, and there you are to meet him. If by any
chance you miss him, you and Paulette are to proceed direct to Paris
and communicate with him at the house of one Jacques Moulin.”
“Oh yes, I know this Jacques person. He came often to buy goods at
the factory and would sometimes come to dine with us.”
“He is a young man?” asked Victor.
“No, quite an old one, not so old perhaps as grandfather but enough
old, for he has grown-up children.”
“That is well,” said Victor with satisfaction. “So then we consider the
next thing.”
“I suppose that is Marchons again.”
“Yes, but not on foot. That will not do. I shall have the honor of
being your coachman.”
“What do you mean? There can be no coaches left here.”
“You may not be overweeningly proud of your equipage, but it is
better than none. At the present moment it lacks a wheel, but that is
a simple matter to adjust, and good fortune for us, for because of
this mishap to the ancient vehicle, it has been discarded, left behind,
so to speak.”
“But how can one travel with but three wheels, or is it one?”
“There are still three, two quite good. From the third, one or two
spokes are missing, but that is a small loss. There must be other
wheels belonging to other carts which are no longer in existence. I
purpose to find one. If it does not match exactly, that makes no
difference.”
“But do you purpose to be steed as well as coachman?”
“Not at all. Behind a dilapidated house in a more dilapidated stable
resides at the moment a small donkey who in some manner has
been forgotten, or rather he was left behind because of the débris
piled around him. No doubt his owner fled in haste and could not dig
him out. I passed by the spot and examined it, discovering that it
will not be so difficult as appears to extricate the beast, so I shall dig
him out and there we have an equipage not to be despised, and
much better than a wheelbarrow in which I might have had to
bundle you and that poor Paulette.”
“Not me, for I could walk.”
“Part way, maybe, but there is no question of that as I see it.”
“What ingenuity, Victor. Who would have thought this out but you?”
“It has been great amusement, I assure you. Bravo! How I shall
enjoy driving Master Donkey. He seems a strong little beast, and was
glad to see me, the coquin. You should have heard his hee haw
when I spoke to him. Now about Paulette, is she able to travel?”
“She is fast recovering. She was stunned by the blow she received
from a falling stone and was weak from loss of blood. It was
wonderful that she escaped being killed outright. I am sure she will
recover even more rapidly when she hears of our good fortune in
having such a courier as Mons. Victor Guerin. It is all very dreadful,
of course, Victor, and last night I felt as if I could never smile again,
but now that my grandfather is safe, Paulette is better, and I have
had some food my spirits have risen.”
“Good! then perhaps you will be willing to go with me to recover
that donkey. Two are better than one at a task like that. Once the
animal is extricated we will feed him, then we will find a wheel for
the cart and can be off for a visit to that cow shed that you were so
loath to leave.”
“Detestable spot, how can you say I was loath to leave it?”
“When one spends an entire night in a place it is a sign that it has its
attractions.”
“Stop teasing. I stayed because there was nothing else to do, as you
well know. I never wish to see the place again.”
“Ah, but you will have to go with me to show me where it is.” Victor
gave her a merry glance.
Lucie shrugged her shoulders. “Well, it may be that so much is
necessary, and perhaps you can discover if there are really any eggs
in that nest. That is something I should like very much to know.”
It required some argument to convince Paulette that Lucie was
necessary to the expedition, but at last she was made to realize that
this was not a time for conventionalities and so the two young
people started off together, first to get out the donkey.
CHAPTER VI
MORE WAYS THAN ONE

THE rescue of the donkey was not quite so easy a task as it looked
to be, but the two young people went at it heartily, Victor removing
the heavier stones and timbers which blocked the way, and Lucie
undertaking the smaller pieces. Master Donkey, whom Victor dubbed
“Long Ears” for want of a better name, meanwhile looked on
attentively, his ears moving in accord with his interest.
At last after an hour of rather exhausting labor, Victor exclaimed:
“There, Lucie, I think I can climb over now and get at Long Ears.
Donkeys are more sure-footed than horses and he can mount this
pile of stuff and pick his way along without doubt. You might stand
there and entice him with a handful of fresh grass.”
Lucie hunted around for such green stuff as she could collect from
crevices and corners, while Victor led forth the prisoner.
“Now he must have some food and drink,” declared Victor. “He must
stand in great need of it, poor fellow, and while he is partaking we
will get that wheel.”
“Where is it?” asked Lucie.
Victor laughed. “Ah, that is the joke of it. I haven’t an idea where it
is. I simply have faith to believe there is one; there must be. Who
ever saw a town that did not contain at least one discarded cart
wheel in the out-of-the-way corner of some stable-yard, or some
such place? I shall prowl around until I find it; that is all. Do you
want to prowl, too?”
Lucie declared herself eager to go with him on this quest, and they
started out, making inquiries as they went along and at last coming
upon the very odd corner that Victor had prophesied and where they
found the cart wheel of their desire. It was rather a dubious looking
affair, and its circumference was slightly less than those on the cart
which Victor had secured, but he declared it would serve, and, with
the help of an old man, managed to fasten it in place. Then they
started off for the cow shed in high good humor.
“It does not go badly, this cart,” maintained Victor, “and as for our
friend. Long Ears, he is none the worse for having served his time in
prison.”
“Ah, do not speak of him in that way,” chided Lucie. “It is as if he
had been a criminal.”
“He may be, who knows what evil deeds he may have done in his
lifetime.”
But Lucie would none of this, and so they argued and made merry
upon that same road over which Lucie had traveled so wearily and
despairingly a few hours before.
They found everything intact at the shed. Victor lifted baskets and
bundles into the cart. “Now we will hunt for those eggs,” he said,
“and we may as well take the hen, too. Some one can make use of
her, and she will find it hard to scratch for a living here.”
“The eggs first. I am so very curious about those eggs, Victor. To
think that after all I shall find them.”
“Shall I climb up, or do you want to see for yourself?”
“I would very much like to see for myself.”
“Then you shall do so. I will lift you up so you can see.”
Lucie looked rather doubtful at this. She was not sure that she would
approve of this way to discovery. “Suppose you should let me fall, or
at least hold me so unsteadily that I should let the eggs fall.”
Victor took her objections good-naturedly. “Then shall I climb up?”
“Ye-es, I suppose you will have to,” admitted Lucie.
“I have it,” cried Victor wanting to indulge her. “I can back the cart
into the shed. There is plenty of room, and you can stand on that
and be perfectly sure of your footing.”
“Oh, Victor, what a perfectly lovely idea,” cried Lucie. And in a few
minutes the cart was standing beneath the shelf while Lucie climbed
upon it. She laughed down at Victor. “It cannot be said that one’s
footing is so very sure after all, for the cart is so rickety.”
“I think it will hold out. I will stand by Long Ears so he will not bolt
at a critical moment.”
Feeling herself doubly safe Lucie turned to view the shelf and what
was thereon. But the instant the head appeared above the top came
again a wild flutter of wings, and a second squawking hen, disturbed
in her retreat, flew in an agony of fright down from her nest and
directly upon the back of the donkey. Victor made a grab at her as
she went sailing by in a second flight, and Master Long Ears no
longer feeling a detaining hand, kicked up his heels and went
clattering out the door, bearing Lucie frantically trying to keep her
feet and to get hold of the reins.
Fortunately the donkey once outside stopped at sight of green fields
and began deliberately to crop the grass. Lucie collapsed in a fit of
mirth upon the floor of the cart. Victor came running out, at first
alarmed, and then ready to join in her laughter.
“It is not meant that I should get at those eggs,” declared Lucie.
“You will have to get them, Victor.”
Monsieur was wounded, night came, no one knew that
he lay there, there were so many. The little dog knew
and he went out to find him.
“But what a remarkable hen,” remarked Victor, “to lay two eggs in a
day.”
Lucie went off again into another burst of laughter. “But, no,” she
cried, “it was not the same hen. That other was brown; this is
speckled. There are then two of them.”
“Ma foi!” cried Victor, “one does not have to go far for a joke even in
these days.”
He returned to the shed, climbed up to the shelf, and presently
reappeared with his pockets bulging. “My first foraging expedition,”
he announced, “and here are the fruits, a half dozen eggs. We will
commandeer these, a reserve for future use. We may be glad
enough of them on our way. As for those hens they will have to fend
for themselves, for there is no time to hunt them.” He deposited the
eggs in one of the baskets, they climbed back again into the cart,
undertook the task of persuading Long Ears to leave his pastures
new, and finally they were on their way back to the town, arriving
without mishap; then, with the consent of such authority as still
existed, they set forth on the more precarious expedition to the next
station.
Victor realized that time was short and it would be a close shave for
him, for he must get back to camp at the proper hour. He had
promised to return the borrowed cart and donkey, but in doing this,
he resolved that he must let the future take care of itself. If he could
not return the borrowed articles in person, some one else could, and
that was all there was to it.
They began the second stage of their journey quite confidently. Life
again appeared worth living. Lucie sat by Victor’s side on the length
of board which served as a seat. Paulette, perched on a similar
board, was surrounded by baskets and bundles. She held firmly to
her green cotton umbrella from which she had not parted in all this
time. Sometimes she used it as a staff, sometimes it was laid across
her shoulders on the top of a pack she carried, again it found a
place on the top of a basket, but wherever it was Paulette evidently
did not mean to lose sight of it. Having renewed his strength the
donkey trotted along bravely enough, but the cart was less
satisfactory. The wheels spread apart in a manner that threatened
collapse at any moment, while the added fourth caused a queer
joggle, a sort of limp, as it were.
“It may not be the most luxurious way of riding,” observed Victor,
“but if we get there it will suffice.”
“Oh, Victor, do you think there is any danger of our not getting
there?” inquired Lucie in alarm.
Victor glanced down at the wavering wheel. “It will be good luck if
we do,” he replied, then seeing Lucie’s look of dismay he added: “but
the donkey is very strong; we can pile the luggage on him, then you
and Paulette can take turns in riding whatever portion of the road
we still have to travel.”
There was some comfort in this, and perhaps it was as well that
Lucie was warned, for at last after a threatening squeak, and a more
than ordinarily violent wabble, off came the wheel and went
careering down a gully at the side of the road. The cart gave a lurch,
but Victor was quick to spring out, and ran to the head of Long Ears
who seemed to have it in his mind either to bolt or to kick out with
his hind legs. He decided upon a mild performance of the latter feat,
but his heels could do little damage to the already decrepit cart, and
under Victor’s management he soon calmed down and stood meekly
while he was being unharnessed.
“Nobody hurt,” announced Victor cheerfully, “and we have not so
very far to go. I think we can manage it. Come, Paulette, let us have
those baskets. We can strap them on Long Ears pannier-wise, and
we can make a pillion of the contents of those bundles, or at least of
part. We can lay those on his back first and the straps which we can
make of the reins will hold them on.”
Paulette was quite used to a peasant manner of traveling, and lent a
hand skillfully, refusing absolutely to be the first to ride, so to Lucie
was given this honor.
Leaving the cart abandoned by the roadside they set off again, Lucie
sitting easily upon her improvised saddle and rather enjoying the
novelty. Victor walked by her side, declaring that one could not tell
what tricks a donkey might suddenly develop and it was well that
one should be on hand. At last Lucie declared that it was Paulette’s
turn to ride, and though at first she protested violently, the old
woman finally was persuaded that Lucie would be made
uncomfortable if she continued to refuse, so she mounted Long Ears
and in this way the little company at last arrived at their destination.
“Now,” said Victor, “the first thing is to discover Mons. Du Bois. If he
be here I can leave you in safety.”
“And if he is not here?” said Lucie with some trepidation.
Victor looked troubled. “I am afraid I shall have to leave you in any
case,” he answered slowly.
“O, Victor,” cried Lucie, “how can we get along without you?”
“Do you want him to be shot as a deserter?” asked Paulette severely.
“He must get back to his regiment, and he has none too much time
as it is.”
“Oh!” Lucie looked distressed. “I did not think, but—” She looked
questioningly at Paulette.
“Do not distress yourself, my child,” returned Paulette imperturbably.
“We shall get on. Monsieur, I beg that you will not embarrass
yourself further. We are not the only women who must travel alone,
and I have not a fear.”
“I trust to you, Paulette,” said Victor heartily. “You remain here. I
shall not be gone long.”
Paulette dismounted from her steed and led him to one side where
they would be less conspicuous. Lucie placed herself in a position to
watch the street down which Victor had gone, and which led to the
railway station. It was there that he intended first to go. He was as
good as his word, for presently Lucie cried: “Here he comes,
Paulette, and there is some one with him? If it should but be
grandfather!”
Paulette looked searchingly at the two approaching figures. “But that
it is not,” she declared. “That is neither the form nor the gait of
Mons. Du Bois.”
Lucie drew a long sigh. “I did so hope,” she murmured.
In a few minutes Victor came up with a stout, middle-aged man.
“This is Mons. Carriere,” he announced. “He will do all in his power
to locate Mons. Du Bois. As for me, I find I must take a train in a
few minutes, but I am glad to leave you in safe hands.”
“How can I thank you for all you have done,” said Lucie, with a look
of regret in her eyes. “I wish you need not go, Victor, but I should
like less your having to be shot.”
Mons. Carriere looked inquiringly at Paulette.
“Mademoiselle means that monsieur must return to his regiment,”
she explained. “If you will believe it, monsieur has spent his entire
leave in transforming himself into an escort for us.”
“It is incredible,” exclaimed Mons. Carriere, turning to look at Victor.
“But, I assure you, monsieur, it was my duty,” declared Victor. “Are
we not in this war as much to protect our women as our land?”
“Well said, brave garçon,” cried Mons. Carriere, “but let me suggest,
monsieur, that if you wish to make that train, your opportunity is
very short.”
With that Victor grasped Lucie’s hands, kissed her upon either cheek,
did the same to Paulette and was off at a run for the station. Lucie
ran a short way the better to see the last of him, and stood where
she could have a view of the train already to be heard approaching.
Paulette wiped her eyes with the back of her hand. “He is pure gold,
that lad,” she said brokenly to Mons. Carriere. “Such courage, such
cheerfulness, such invention! When I think that he may be fodder for
cannon I cannot endure it.”
“It is such as he will save France,” returned Mons. Carriere. “We
must be willing to let them go, to die, perhaps, for their country.
Death is not the end.”
“You perhaps have no son to sacrifice,” returned Paulette.
“I have three,” replied he quietly, “and you, madame?”
“I have one and one only. He is a poilu like yonder lad.”
“But you do not weep that he gives himself for his country?”
“I weep in secret, but also I am proud that he was one of the first to
go.”
The train was now moving out of the station. Paulette turned her
back upon it, but Lucie stood waving farewells to Victor, who in
response waved his adieux.
As Lucie came up Paulette wiped her eyes, turning to Mons. Carriere
to say hastily: “Do not let us mention Monsieur Victor, if you please.”
“He has gone, Paulette,” cried Lucie. “Is he not fine and brave? Ah
me, I wish—”
“Cela ne fait rien,” Paulette interrupted with a shrug of her
shoulders. “The next thing is to find Mons. Du Bois. What is gone is
gone.”
“Do you think it possible that my grandfather is here?” Lucie asked
Mons. Carriere.
“It is very possible. This young poilu, who has just left, charged me
to take you to a safe place, to house the donkey and to return it to
one Jacques La Rue when opportunity came. Allons, then, to my
house we go and then proceed to investigate. You are able to walk,
madame? By the way, have you been hurt that your head is bound
up in such fashion?”
“She has shed her blood for France,” cried Lucie. “That wound was
caused by the enemy.”
“Ma foi, what a fantasie!” cried Paulette. “I assure you, monsieur,
that my hurt was caused simply by a falling wall. I was passing; the
wall gives way, the brick descends upon my head; that is all.”
“Ah, but the falling wall, that came from the bombs of the enemy,”
persisted Lucie. “Is it not, monsieur, that she has suffered for
France?”
“Most surely,” he answered. “She has been wounded, though
indirectly, by the enemy, and so is to be honored as a soldier.”
“There,” exclaimed Lucie, “it is as I said, Paulette.”
“La la,” she responded, “this sort of argument is a thing to make one
laugh, and quite aside from our business. Where is it we go,
monsieur, without wasting more words or time?”
“We go to my house where you rest until I have completed my quest
for Mons. Du Bois. If I do not discover him, then we will see what
can be done about your pursuing your journey to Paris. Meanwhile
you have nothing to do but make yourselves comfortable. My
housekeeper will see to that, I assure you.”
“But, monsieur,” Paulette began protesting.
He lifted his hand to silence her. “It is nothing. In these days one
takes what comes and says no word.”
They followed him up the street, turned a corner and halted before a
house which reminded Lucie of her own home. A green gate set in a
white wall led, probably, into just such another garden as she had
left so regretfully. It was through this gate that they entered, and,
true to Lucie’s expectations, the garden was there, holding the
familiar trees and flowers which spoke to her of home. Her lips
trembled and her eyes filled with tears. She stole a glance at
Paulette whose face had a wooden expression. She was looking
neither to the right nor left.
“Marianne,” called Mons. Carriere.
A stout, middle-aged woman came to a side door.
“We have guests,” announced Mons. Carriere. “See that they have
everything to make them comfortable. They have passed through
grievous scenes, Marianne. They are victims of the war. This good
woman, you see, has been wounded, and mademoiselle here has
become separated from her parents, has passed the night alone in a
cow shed in the very track of the enemy.”
“Mon Dieu!” cried Marianne, hurrying down the steps. “Certainly,
monsieur, they shall of the best. I, myself, will see that they are
cared for. Enter, madame. Enter, mademoiselle. I am honored.”
They passed into the house, where Marianne bustled about in great
excitement and presently a plentiful meal was set before them to
which Mons. Carriere left them while he went forth upon his errand
of inquiry. It was not long before Paulette and Marianne were
chattering together like old friends, their conversation interspersed
with many pious ejaculations, and on Marianne’s part with many
expressions of astonishment. Soon tiring of their talk Lucie stole out
into the garden, finding it upon closer investigation very like, yet
unlike, her own. There was no stone bench. There was no cherry
tree overhanging the wall over which she might see Annette’s face
appear. She wondered what Annette was doing. This recalled Pom
Pom, whose achievements had been made the subject of some of
Paulette’s recital. She wondered where he was. In the excitement of
her parting from Victor, and in reaching this haven of rest, she had
not thought of much except the possibility of soon seeing her
grandfather, forgetting for the moment all about the little dog. The
last she had seen of him he was at the station at Victor’s heels.
Starting up from her seat in alarm she was about to reënter the
house when she heard at the gate a little whining sound, then a
quick sharp bark. “Pom Pom,” she called, “is it then you?”
A joyful bark answered. She ran to the gate, admitting the little
creature, who jumped upon her in wild delight. “I wonder where you
have been,” said Lucie, gathering him up in her arms. Pom Pom tried
to explain in dog language, but Lucie did not understand that he was
trying to tell her of his adventures, and that he had followed for
some distance a rapidly moving something which was bearing away
his beloved master, that finding he could not overtake this galloping
monster he had returned to the station, nosed about till he caught
the right scent and so had traced his second best beloved to this
present spot.
“I suppose you are hungry,” remarked Lucie.
Pom Pom quite understood this and answered accordingly. His
answer brought Marianne to the door. “Is it this so wonderful dog
you have there?” she asked. “He shall have food of the best. If he
prefers, mademoiselle, he shall have it there in the garden. I will
bring it to him.”
She went off, soon returning with a dish of meaty scraps and a pan
of milk upon which Pom Pom set to work without delay, finishing up
by licking both pan and dish. Then he lay down contentedly at
Lucie’s feet.
She had settled herself comfortably in a high-backed rustic chair
which stood invitingly in the shade. It was a delightful resting place.
The flitting of birds, the hum of bees, the odor of flowers, gave her a
homelike feeling. She was very tired, she realized, for she had
endured a rough journey, and her sleep of the night before had been
none too sweet. It was a kind Providence which had led her into
such a spot as this, yet, she reflected, it was all of Victor’s doing.
Grandfather, where was he? When would she hear from her parents?
What of Annette? These and other wandering questions passed
through her mind, becoming more and more vague till finally both
little dog and little girl were sound asleep.
CHAPTER VII
A STRANGE GARRET

THE shadows had grown very long and the sunset light in the
western sky had faded to a twilight hue when Lucie was suddenly
awakened by a sharp bark from Pom Pom. She sat up expecting to
see a more familiar face than that of Mons. Carriere who bent over
her. Pom Pom, as protector, was protesting against the too near
approach of any one save a member of the family. As soon as Lucie
came to a realizing sense of where she was, she sprang up asking
eagerly: “My grandfather? Have you found him?”
“Alas, no, my child,” was the disappointing reply. “It seems that he
has not reached this town as yet.”
“But what—where is he then?”
Mons. Carriere hesitated. “That one cannot tell at once. In these
times a thousand things might happen. He may have been turned
aside on account of danger from the guns. He may have taken
another road, a longer, though perhaps better. It will do no harm to
wait a little. Give him time. You are more than welcome to remain as
my guest. Content yourself, my child. If, after a reasonable time, he
does not come, then we will see what next.”
“But monsieur—” Lucie began to protest.
“La la, there is nothing to say, not a word. Let us go in and see what
that Marianne has for us.”
There was indeed nothing to do but to accept the hospitality so
readily offered, so Lucie went in, but though her host did his best to
make her feel at ease and to declare himself fortunate in having the
opportunity of entertaining a guest at table, Lucie felt too troubled to
enjoy her meal very much, though she realized that Fate had been
kinder to her than to most refugees. She made an effort to appear
cheerful, but her wistful smile went to Mons. Carriere’s heart, and
made him even more fatherly in his manner toward her.
He left her to Paulette when the meal was over, and then these two
conferred together.
“I am troubled, so troubled, Paulette,” said Lucie. “I am most
unfortunate. My father wounded, my mother lost, my grandfather
who knows where?”
“Take heart, my child, it is not so bad as it appears,” Paulette made
the effort to console her. “It is much better than yesterday when
your only shelter was a cow shed and you were entirely alone. Your
father lives, we are assured, and since he has recovered thus far we
may believe that he has turned the corner. Your mother is with him,
no doubt, and as for your grandfather, there is no need to worry
about him, for he is with friends who will look after him. One must
do what one can in these times, and I have my belief that we shall
find him in Paris waiting for us.”
“Then do we go on at once?”
“Not at once. In another day, I think. We must give them another
day. This is a good place. One finds it peaceful, restful. This
Marianne so friendly, monsieur so kind. Yes, it is not showing
appreciation to hurry away without reason. Another day, chèrie. We
will take a good night’s rest and let the morrow take care of itself.”
“Do you think grandfather will be here then?”
“It may be. If not we shall meet him in Paris. We have had that
message of his. It is enough.” And with this Lucie was obliged to be
satisfied.
It had been an eventful day, but its excitements appeared to Lucie
no greater than those to which she looked forward in that great city
of Paris, which place she half feared, then longed to see. Was it
there that their home was to be henceforth, and what would it be
like? She could not form any picture of it in her mind, but wherever
it might be it was there that she would next see her parents. She fell
asleep wondering how soon they would all be united, and slept
soundly, the “so intelligent dog” curled up at her feet.
She awoke bright and early the next morning, at first imagining
herself back in her own room, though she soon perceived the
difference and sat up, the better to observe what she had failed to
take in the night before. It was a clean, orderly little room adorned
with such things as appeal to a young man’s taste, and she
concluded that one of those three sons must have occupied it before
he went soldiering.
“At least it is not a cow shed,” she remarked to Pom Pom, “although
for my part I do not care for those funny things upon the wall.” She
was attracted by a pair of foils and fencing gloves at which she
looked curiously, then gave her attention to other manly adornments
of the room. These, however, did not keep her attention very long,
for she remembered the eventful journey which was probably before
her, and soon made ready to go downstairs to glean such news as
might have been gathered during the night. She found Paulette still
in the rôle of heroine recounting her adventures to a group of
Marianne’s friends. She stopped short at sight of Lucie and the little
company of gossips dispersed so that Lucie was left alone with
Paulette, whom she began to consider rather a person of importance
who might very well direct their future plans.
“What news? What news?” she asked. “Has anything been heard of
my grandfather?”
“Nothing,” replied Paulette, “and no news is good news. As for other
things they say the Germans are still advancing and that the people
are flocking from the villages by thousands. Those that do not flee
must remain to be under German rule. We are lucky, we, to have
come when we did.”
“What would have happened if we had stayed?”
“If we were not killed by the bombardment, we would have been
caught like rats in a trap.”
“Would they have killed us?” asked Lucie in horror.
“One cannot say, but for my part I should not like the idea of being
forced to obey a boche.”
“But do you think, could it be that mother and grandfather have
been caught that way?”
“Pst!” Paulette made a scornful snap of her fingers. “Dispose of that
notion. We shall hear quite otherwise. We shall know the truth about
them before long. In Paris everything is known. They say that one
cannot wink without the thing being known by the police.”
“What do we do first when we get to Paris?” Lucie inquired, full of
curiosity. “Where do we go? Is it to a place we shall live till my
parents arrive, and will it be in the heart of the city or in the
suburbs? Shall we have a garden, do you think?”
“La la,” cried Paulette, “what questions! How is one to tell till we get
there?”
“Shall we have plenty of money? Are we going to be very poor?
Have you enough in case grandfather is delayed in coming?”
“Such questions!” cried Paulette again. “We shall not at once starve,
though what is in the future who can say? The business is a thing of
the past; it is no more, and one must exercise economy of course,
but we shall see what we shall see. Rest tranquil for the present, my
pigeon; to-day we shall dine.” And no more could Lucie learn.
Though anxiously looked for, no news of Mons. Du Bois came that
day. Acting on the advice of Mons. Carriere, Lucie wrote to her
grandfather in the care of Jacques Moulin, and then Paulette
determined that they must set out the next morning, although Mons.
Carriere protested, and begged that they would remain where they
were till something definite had been learned about Mons. Du Bois.
But Paulette, with the obstinacy of her class, insisted that there was
but one thing to be done, and that was to carry out Mons. Du Bois’s
orders. He had said that if they missed him, failed to meet him in
this town, they were to go on to Paris and communicate with him
there, so to Paris they must go and that was the end of it.
Their good host did all that he could to smooth the way for them. He
directed them to a small and inexpensive hotel, urged them to let
him know how they fared and if in any difficulty to notify him, so
they set out quite cheerfully and hopefully.
The journey occupied more time than they supposed it would, for
the distance was not great and in ordinary times would have taken
but a few hours, but now there were frequent stops, cautious and
slow advances, but at last Paris was reached and they stood on the
platform of the Gare du Nord, Paulette still holding fast to her green
umbrella and Pom Pom capering about in delight at being released
from confinement. They drove to the quiet little hotel which Mons.
Carriere had recommended, and here began Lucie’s life in Paris,
whether to be of long or short period who could tell?
It was rather disappointing to Lucie from the outset. The small hotel
seemed a stuffy, shabby place after the daintiness and freshness of
her own home. Paulette was overcome with fear at the traffic in the
streets and dared not venture out, nor would she for a moment
allow Lucie to go.
“You? Alone? A young maid in the streets of Paris? Ciel!” she
exclaimed. “It would be as a lamb among wolves. No, no, my child,
it is not to be thought of.”
“But, Paulette,” protested the girl, “it is so stupid here. I thought
Paris would be very gay, and here in this dark little street where one
can see so little it is anything but gay, and I do not like it.”
“One cannot look for gayety in war time,” returned Paulette grimly,
“and what one wants is not what one may look to receive.”
This Spartan-like response was very discouraging, and leaving
Paulette to arrange and rearrange the various baskets and bundles,
Lucie went to the window to gaze out into the street. A dismal rain
was now falling, and such little light as might be was intercepted by
the tall buildings opposite. It was not a very pleasing outlook and
there was nothing going on in the street itself that particularly
invited attention, yet Lucie, in order to pass away the time, sat for a
long time with elbows on the window sill, looking out.
She was aroused by a sudden remark of Paulette’s. “One cannot
afford this very long,” she said. “Unless we hear from your
grandfather by to-morrow morning we must seek this Mons. Moulin.”
Lucie turned away from the window and seated herself upon a worn
and faded armchair. “But, Paulette, you tell me you are so afraid in
the streets, and how could we ever find the way, in the rain too?”
“Are there not telephones?” returned Paulette.
Sitting on the topmost step, her head buried in her arm,
sobbing her heart out.
“To be sure. We might have thought of that at once, and so relieved
our minds. Will you go down with me and see about it now,
Paulette? We know the address so it should not be difficult to find it
in the book. Shall we go?”
“The sooner the better,” responded Paulette. So down they went to
the telephone below. Paulette grudgingly produced the necessary
coin to pay for the call, and after some delay they managed to get
hold of the operator, but after what seemed an unconscionable time
they were informed that no response came to the call.
“It is probably a place of business and too late to find the
proprietor,” suggested the old man in charge of the office. “To-
morrow, mademoiselle, in the morning, no doubt you will find him
without difficulty.”
But in the morning they met with no greater success. “No answer,”
reported the operator.
“What can it mean?” Lucie turned in bewilderment to the old man.
“Probably this person has moved away.”
“Then what shall we do?”
“One would best go to the place and find out. There are neighbors,
no doubt, who can tell where the person has gone.”
“We shall have to go. There is nothing left to do,” said Lucie, turning
to Paulette. “Is it far, monsieur?” she asked. She showed the old
man the slip of paper on which she had written the address.
He read it and shrugged his shoulders. “Far enough.”
“But one can walk?” put in Paulette.
“Perhaps, if one knows the way; otherwise one must ride. A cab is
not so easy to procure these days; an omnibus, perhaps. It will be
much cheaper.”
“The cab, no. I will not go to the expense,” declared Paulette firmly.
“As to the omnibus—well, that too is a venture. How does one tell
when to get out? It is all very bewildering, this.” Always a resourceful
person, she now looked more worried than Lucie had ever seen her.
“Perhaps we could find some one to go with us,” the happy thought
came to Lucie.
“That is well thought of,” said the man, who was a good sort and
really quite concerned. “At another time I could accompany you
myself, but in these days—” He shook his head. “I am here to look
after the business of my son who has gone to the war, I who
thought myself retired and comfortable for the rest of my days. But
what will you? I cannot let the business go to the dogs. It is bad
enough as it is, yet one must hold on to it. I will think what can be
done. My grandson might go; he is at school, but when he returns
we shall see.”
This relieved the situation in most directions, though Paulette had
many misgivings about trusting herself to the guardianship of so
young a lad as the little André was, and went forth in fear and
trembling. Lucie, on the contrary, was delighted at being able to see
something of the city. The rain had ceased, though it was still
cloudy. André chattered away, pointed out landmarks, answered
questions glibly, and was altogether a very satisfactory companion.
Lucie thought Paulette stalked along with the air of being ready to
challenge any one who looked her way, and though she bore herself
stoically when they came to the crowded crossings, Lucie could see
that she was in an agony of fear and dread.
At last they reached the street and number which should be that of
Jacques Moulin’s establishment. It was closed, doors locked,
windows barred. A notice read: “Fermez; le propriétaire est sous les
drapeaux.”
“Mon Dieu!” exclaimed Paulette, “but this is a thing terrible.”
Lucie was not so easily daunted. “We will inquire next door,” she
said, and forthwith proceeded to investigate.
An elderly man answered her questions. “Jacques Moulin?” Yes, to
be sure. He had gone, departed to the war. The business had been
suspended until after the war; who knew how long that might be?
Had one Antoine Du Bois been here recently inquiring for this same
Moulin? The man considered. He shook his head. No, there had been
no one of that name, of that he was positive.
Entirely at a loss what to do next, the little party turned away after
having secured the address of the firm with which Jacques Moulin
had consolidated. Paulette scarcely spoke on the way back; she was
too deeply occupied with puzzling out plans for the future. Lucie,
too, though she kept one ear open for André’s chatter, was disturbed
in her mind.
“What are we to do, Paulette? What are we to do?” she asked once
they were back in their rooms.
Paulette dived down into the depths of a pocket under her petticoats
and drew forth a queer little pouch the contents of which she shook
out into her lap, many sous, some franc pieces, a few five franc
coins, one paper note. She counted it all over laboriously. “This will
serve for a time,” she said at last, “and then the deluge. At once we
must find cheap lodgings, and then I shall look for employment; it
should not be difficult to find this when so many men have gone. I
shall succeed. Oh yes, I shall succeed.”
Lucie sat mute and distressed while Paulette made her calculations.
“But, Paulette,” she broke out finally, “is it necessary to do this? My
grandfather surely will appear very soon, and then there is my
father’s pay. When he knows our needs, of course he will see to it
that we have money.”
Paulette looked at her pityingly. “Pauvre petite, one may not look at
things through such rose-colored glasses. It might happen that the
affair would run smoothly, but how do we know that your father is
yet well enough to attend to such matters? This in the first place,
and in the second it might delay his recovery if he were given cause
to worry. Again, affairs of government are not arranged in a
moment. Papers must be prepared, sent to this one, that, and who
knows how many months may pass before all is arranged?
Meanwhile are we to sit and suck our paws like bears?”
“You know a great deal, don’t you, Paulette?” said Lucie much
impressed.
“I have ears. I know what I hear,” returned Paulette. “Moreover,” she
went on, “who am I that I should not work? I have always worked,
even as a little child. I should be lost, desolated, without work. Am I
to sit up like a lady and fold my hands at my time of life? No, no, the
sooner I get to work the better.”
“But I cannot bear the idea of your working to feed me,” said Lucie.
“And who has a better right? Did I not nurse you, and have I not
served your family always, always.”
“Nevertheless,” began Lucie.
“La la, if it comes to that,” interrupted Paulette, “when I am too old
to work we can settle the score. That is finished. Now something
else. We telephone to these people whose address you have just
learned. We learn what we learn. Then at once we look for other
lodgings. When we leave here we leave the new address with the
old one so that any may know where to find us. That is all.” She
carefully replaced the money, securely tied up the little bag and put
it back in her deep pocket, then rose to carry out the plans she had
made.
At the end of twenty-four hours Paulette had accomplished what she
set out to do, and Lucie found herself high up in an attic room, in an
old part of the city. “It is not magnificent but it will serve,” was
Paulette’s comment as they took possession. Lucie made no answer.
It seemed a mean and poor habitation to her. Its one redeeming
feature was a window which overlooked what had been an old
convent garden, and gave opportunity for the sun to find its way into
the room, and for the girl to see a bit of sky above the housetops.
She foresaw that this would be her favorite spot, and that a chair by
the window would save her from a feeling of utter desolation. “All
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!

ebooknice.com

You might also like