MongoDB

Learn One Of The Most Popular NoSQL Databases

Derek Rangel

Derek Rangel Copyright © 2015

All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the author, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law.

Table of Contents

Introduction

Chapter 1- Definition

Chapter 2- Environmental Setup

Installation of MongoDB in Windows

Installation of MongoDB in Ubuntu

Chapter 3- Creating a Database

Chapter 4- Dropping (Deleting) the Database

Chapter 5- Creation of a Collection

Chapter 6- The “insert()” method

Chapter 7- Dropping (Deleting) a Collection

Chapter 8- Querying the Collection

The “OR” operation in MongoDB

Combination of “AND” and “OR”

Chapter 9- Updating a Document

Chapter 10- Deletion of a Document

Removing a single one

Removal of all of the Documents

Chapter 11- Projection in a MongoDB

Chapter 12- Limiting of Records

Chapter 13- Sorting of Records in MongoDB

Chapter 14- Aggregation in MongoDB

Chapter 15- Creating a Backup in MongoDB

Chapter 16- Deployment

Chapter 17- Text Search in MongoDB

How to enable Text Search in MongoDB

How to Delete an Index

Chapter 18- Regular Expressions in MongoDB

How to use the “regex” expression

Making the “regex” case insensitive

Chapter 19- MongoDB and Java

Creation of a Collection

Selecting a specific collection

Inserting a Document

Retrieval of Documents

Updating a Document

Conclusion

Disclaimer

While all attempts have been made to verify the information provided in this book, the author does assume any responsibility for errors, omissions, or contrary interpretations of the subject matter contained within. The information provided in this book is for educational and entertainment purposes only. The reader is responsible for his or her own actions and the author does not accept any responsibilities for any liabilities or damages, real or perceived, resulting from the use of this information.

The trademarks that are used are without any consent, and the publication of the trademark is without permission or backing by the trademark owner. All trademarks and brands within this book are for clarifying purposes only and are the owned by the owners themselves, not affiliated with this document.

Introduction

MongoDB is one of the leading NoSQL (Non Structured Query Language) databases in use today. It can be used for various purposes,  as well as for linking with programming languages while developing our applications. This is why you need to know how to operate MongoDB. This book will guide you in this.

Chapter 1- Definition

MongoDB is one of the leading NoSQL databases. It is an open-source and document database which was written in the C++ programming language. It is used for the development of relational databases since it provides us with a traditional table approach to development of the database. Its schemas are well known for the dynamism that they offer, making the integration of data in particular types of application much faster and easier.  MongoDB is a cross-platform database, and it offers a high availability, performance, and scalability and this is why it is liked by most database developers. The software is open-source, meaning that you can download and use it for free. In this book, we will explore the features of the database, and some of the functionalities that it offers.

Chapter 2- Environmental Setup

Installation of MongoDB in Windows

If you need to install MongoDB in your Windows platform, begin by downloading it from its respective site < https://www.mongodb.org/>. Make sure that you have downloaded its latest version and the right version for the operating system that you are using and the processor architecture. If you need to know the version of the Windows OS that you are using, just open the command prompt and then execute the following command:

In my case, I get the following regarding the architecture of my system:

If you are using a 32 bit version of the Windows OS, then the system can only support a database not larger than 2GB in size, and this is only suitable for evaluation and testing purposes. Once the download process has completed, identify a suitable directory and extract the download in it. The name of the folder where the extraction has been done should be “MongoDB-win32-i386-[version].” It can also be “MongoDB-win32-x86_64-[version}”\, where the “version” is the version of the MongoDB that you have downloaded.

Once the extraction has been done, open the command prompt, and then run the command shown below:

If you had done the extracting of the MongoDB in another directory, navigate to the directory, and then execute the command given above.

For the purpose of storage of files, MongoDB requires a folder. The default location of this folder is “c:\data\db.” This means that you have to manually create this folder by executing the command given below:

In case the installation of the MongoDB was done in any other directory, then the alternative path to the folder “\data\db” needs to be specified.

Once you are done with the above step, open the command prompt, and then navigate to the “bin” folder located in the directory where the MongoDB has been installed. Use the “cd” command so as to navigate to this folder. The following commands can be used for this purpose:

When you see the message “waiting for connections” on the screen, just know that your MongoDB is successfully running. The database is now ready to be run. You just have to open the command prompt and then execute the following command:

In my case, the above command gives me the following output:

The output clearly shows that the MongoDB was successfully installed into the system. You have now learned how to successfully install the database into the Windows operating system.

Installation of MongoDB in Ubuntu

You need to begin by importing the public GPG encryption key for MongoDB. This can be done by executing the command given below:

You then have to create a file named “/etc/apt/sources.list.d/MongoDB.list” by use of the following command:

You can then use the following command so as to update the repository:

Once the update has been completed, you can install the MongoDB by use of the following command:

In my case above, I have installed the latest version of MongoDB which is on the market. Make sure that in your case, the latest version of the MongoDB has been installed. The installation of MongoDB should run successfully. Once it is completed, you have to start the MongoDB. This can be done by use of the following command:

To stop the MongoDB from running, just use the following command:

If you need to restart the database, just run the command given below:

To use the MongoDB, execute the following command:

The above command will connect you to an instance of the MongoDB which is running.

If you want to know more about the commands which are supported in MongoDB, just run the following command:

db.help()

The list of the commands which are available in MongoDB will be displayed once you run the above command.

You might also need to get statistics about the MongoDB server. In this case, open the MongoDB client and then execute the following command:

db.stats()

When the above command has been executed, you will know the name of the database, as well as the number of documents and collections that are contained in the database.

Chapter 3- Creating a Database

In this case, we need to create a new database in our system. The database should not already be in existence. If the database that we specify is in existence, then the command for creation just returns that database, meaning that it has no effect on it. To create a new database in MongoDB, we use the command “use DATABASE_NAME.” The syntax for the command is given below:

Suppose you want to create a new database and then give it the name “mydatabase,” the following command can be used:

use mydatabase

If you need to see the database which you are currently working on or the one that you have selected, use the following command:

The current selected database will be printed with the above command. If you need to see all the databases which have been created in your system, just run the following command:

However, with the above command, you will notice that the database which you have created recently will not be displayed. The reason is that you have not yet inserted something into the database. This means that for a database to be displayed, something must be inserted into it.

Assuming this database is the one which is currently selected, just run the following command so as to insert something into it:

db.mydatabase.insert({"name":"John"})

Once you have inserted the above into the database, you will be able to see your database once you have executed the command for showing the available databases in the system. This is shown below:

You need to note that in MongoDB,, the default database is “test.”  In case you fail to create any other database, any collection that you create will be inserted into this database.

Chapter 4- Dropping (Deleting) the Database

Dropping a database means deleting it. In MongoDB, we use the command “db.dropDatabase()” so as to do this. For the database to be dropped, it must be existing. The syntax for the command is given below:

Note that in the above case, we have not specified the name of the database which is to be deleted. In that case, if you execute the command, then the database which has been currently selected will be deleted. However, it is possible that no database  has been selected. In this case, the command will delete the default database in the system, which is the “test” database. Let us demonstrate how this can be done by use of a practical example:

Begin by issuing the command “show dbs,” so as to list the databases which are available in your system. This is shown below:

As shown in the above figure, I only have two databases in my system. Suppose that I want to delete the database “mydatabase” from my system, I have to use the following sequence of commands:

As shown in the figure, I have begun by selecting the database that I want to delete. It is after this that I have deleted the database. The commands should have deleted the database from the rest of the available ones in the system. However, it is good for you to verify whether this ran correctly. The following command can be executed for this purpose:

show dbs

This is shown below:

As shown in the above figure, the database is no longer available, meaning that our deletion operation ran successfully.

Chapter 5- Creation of a Collection

In MongoDB, we create a collection by use of the method “createCollection(),”. The method takes the following syntax:

db.createCollection(name, options)

In the above example, “name” represents the name of the collection which is to be created. The parameter “options” is just a document, which is used for representation of the configuration of the collection. The options in this case are in terms of the indexing and the size of the memory.

While  inserting the collection, the size of the field of the capped collection is first checked by the MongoDB, and then the max field is checked. The method takes the syntax given below:

Note that in the example given above, our “createCollection()” method has no parameters, meaning that this is the syntax which it takes when it has no parameters.

If you need to see the collections which are available on your system, just run the following command:

show collections

In my case, I get the following:

Consider the example given below:

>db.createCollection("testcol", { capped : true, autoIndexID : true, size : 6352812, max : 10000 } )

{ "ok" : 1 }

>

In MongoDB, one does not have to create a collection. The reason is because once you have inserted a document, a collection will be created for you by the MongoDB.

Chapter 6- The “insert()” method

This method is used when we want to insert data into a collection which is contained in our MongoDB database. Alternatively, we can choose to use the “save()” method for this purpose.

The “insert()” command takes the syntax given below:

>db.COLLECTION_NAME.insert(document)

When you use the syntax given above, then the document will be successfully inserted into the collection.

Consider the example given below:

>db.collection1.insert({

_id: ObjectId(1234),

title: 'Introduction’,

description: 'This is an introduction to MongoDB',

by: 'Lecturer 1',

url: 'http://www.lecturer1.com',

tags: ['MongoDB', 'database', 'NoSQL'],

likes: 150

})

In this case, we have used a collection named “collection1,” which is the one we created in our previous chapter. Suppose that the MongoDB does not find this collection,. What will happen? In this case, MongoDB will create the collection as a new one, and then insert the document which you have specified into the collection. Also, in the document to be inserted, if the parameter “_id” is not assigned to it, then the MongoDB automatically assigns to it a unique objectId. Every document which is inserted into a collection in MongoDB must contain the parameter “_id” which occupies only 12 bytes. These 12 bytes are divided as follows:

_id: ObjectId(3 bytes machine id, 4 bytes timestamp,  3 bytes incrementer, 2 bytes process id,)

You might need to pass multiple documents in a single “insert()”  query so that they can be inserted into a collection. In this case, these documents should be passed into an array. An example of this is given below:

>db.collection2.insert([

{

title: 'Introduction,

description: ‘An introduction to the MongoDB database’,

by: ‘Lecturer 1’,

url: 'http://www.lecturer1.com',

tags: ['MongoDB', 'database', 'NoSQL'],

likes: 150

},

{

title: 'NoSQL Database body',

description: ‘A description of what the database contains’,

by: 'Lecturer1',

url: 'http://www.lecturer1.com',

tags: ['MongoDB', 'database', 'NoSQL'],

likes: 100,

comments: [

{

user:'student1',

message: 'A very nice lecture',

dateCreated: new Date(2015,08,12,3,45),

like: 50

}

]

}

])

That is how we can use a single query so as to insert multiple collections into a collection. Notice that we have passed the documents into an array. Alternatively, we could have used the method “db.collection2.save(document)” for the purpose of inserting the documents into the collection. In this case, we will have used the “save()” method. In case when using this you do not specify the parameter “_id” for the document, the behavior will be the same to what we have in the “insert()” method, meaning that a default objectId will be created and then assigned to the document.

Chapter 7- Dropping (Deleting) a Collection

If you need to drop (delete) a particular collection from your database in MongoDB, use the method “db.collection.drop().” The method takes the syntax given below:

db.COLLECTION_NAME.drop()

We need to demonstrate how one can drop a collection from their database by use of an example. The following sequence of commands can be used for this purpose:

We have a database named “database1.”  The first step should be to check for the collections which are contained in the database. The following sequence of commands can be used for this purpose:

We then need to drop the above collection with the name “collection1.” The following command can be used for this purpose:

As shown in the figure, it is very clear that we have used the name of the collection so as to delete it. This means that only the collection which we have specified will be deleted, but the rest will not be affected. Once you have executed the command, it is good for you to confirm whether the deletion of the collection ran successfully. The following command needs to be executed for this purpose:

As shown in the above figure, it is very clear that our collection named “collection1” is no longer available. This shows that it was successfully deleted from our database. That is how one can delete a collection in MongoDB.

Once you have run the drop() method so as to delete a collection, then you should get a “true” if the process was successful, otherwise, you will get a “false.”

Chapter 8- Querying the Collection

It is a common practice for database users to query for data from the collection. In MongoDB, this can be done by use of the “find()” method. This method takes the syntax given below:

db.COLLECTION_NAME.find()

When you use this method, the documents which are contained in the document will be displayed in a way which is not structured. However, this is not interesting to most people, as they will need to have the results displayed in a manner which is very structured. There is a method which can be used for this purpose.

The “pretty()” method

This method solves the problem which is associated with the “find()” method, as its results are usually well formatted. The method takes the syntax given below:

db.collection1.find().pretty()

Consider the example given below, which shows how this method can be used:

>db.collection2.find().pretty()

{

"_id": ObjectId(9cf68fd8704d),

"title": "Introduction to MongoDB",

"description": "A description of MongoDB has",

"by": "Lecturer1",

"url": "http://www.lecturer1.com",

"tags": ["MongoDB", "database", "NoSQL"],

"likes": "150"

}

>

Other than the “find()”method, MongoDB provides the “findOne()” method, which we can use to return only a single document.

The “AND” operation in MongoDB

Consider the example which is given below demonstrating how the “AND” clause can be use for the querying of data in MongoDB:

>db.collection1.find({"by":"Lecturer1","title": "Introduction to MongoDB"}).pretty()

{

"_id": ObjectId(9cf59at800f),

"title": "An Overview of MongoDB",

"description": "A description of what MongoDB is",

"by": "Lecturer1",

"url": "http://www.lecturer1.com",

"tags": ["MongoDB", "database", "NoSQL"],

"likes": "150"

}

>

With the above query, we should be presented with all the tutorials whose title is “An Overview of MongoDB” and the ones which have been written by “Lecturer1.” The equivalent of the above will be as follows:

where by='Lecturer1' AND title='An Overview of MongoDB' '

If wish to, any of the key value pairs can be passed to the find clause.

The “OR” operation in MongoDB

For us to use this operation in querying of the database, the keyword “$or” must be used. It takes the following syntax:

>db.collection1.find(

{

$or: [

{key1: value1}, {key2:value2}

]

}

).pretty()

Consider the example given below, which shows how this clause can be used so as to query the database in MongoDB:

>db.collection1.find({$or:[{"by":"Lecturer1"},{"title": "An Overview of MongoDB"}]}).pretty()

{

"_id": ObjectId(6ff98cd8942d),

"title": "An Overview of MongoDB",

"description": "A description of what MongoDB is",

"by": "Lecturer1",

"url": "http://www.lecturer1.com",

"tags": ["MongoDB", "database", "NoSQL"],

"likes": "150"

}

>

That is how we can use the “OR” clause to query a MongoDB collection. The query will return a document whose title is “An Overview of MongoDB,” or the one which was written by “Lecturer1.” If both are found, then they will both be returned to the user.

Combination of “AND” and “OR”

These two clauses can be combined, and then used together to query the MongoDB collection. If this is the case, then the search in the collection will have been greatly intensified. Consider the example given below which shows how this can be done:

>db.collection1.find({"likes": {$gt:120}, $or: [{"by": "Lecturer1"},{"title": "An Overview of MongoDB"}]}).pretty()

{

"_id": ObjectId(8ef68bd7912d),

"title": "An Overview of MongoDB",

"description": "A description of what MongoDB is",

"by": "Lecturer1",

"url": "http://www.lecturer1.com",

"tags": ["MongoDB", "database", "NoSQL"],

"likes": "150"

}

>

When the above query is executed on your system, the result should be the list of documents whose likes are greater than 120 and those whose title is “An Overview of MongoDB” or the ones by “Lecturer1.” The equivalent Structured Query Language (SQL) statement for the above should be as follows:

'where likes>120 AND (by = 'Lecturer1” OR title = ‘An Overview of MongoDB’)'

Chapter 9- Updating a Document

Whenever you need to update a document which is contained in a collection in MongoDB, use the “update()” and “save()” methods. When the “update()” method is used for the updating of the collection, the individual elements which are contained in the document are updated, whereas if the “save()” method is used, the existing collection is replaced or overwritten by the new document.

The “update()” method

With this method, the values contained in the existing document are updated. The method takes the syntax given below:

db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

Consider a collection named “collection1,” which has the following data in it:

We now need to replace the tile named “An Overview of MongoDB” with the title “MongoDB Exploration.” This can be achieved by use of the following method:

>db.collection1.update({'title':'An Overview of MongoDB},{$set:{'title':'New MongoDB Exploration'}})

>db.collection1.find()

{ "_id" : ObjectId(9854548745361adf45bd4), "title":"An Overview of MongoDB"}

{ "_id" : ObjectId(9854548768561adf45bd5), "title":"A NOSQL Database"}

{ "_id" : ObjectId(9854548743221adf45bd6), "title":"An overview by Lecturer1"}>

The above code will achieve that. However, you need to note that the default setting for MongoDB is that it will update only a single document. In case you need to update more than one document, the parameter “multi” must be set to true. This is shown below:

db.collection1.update({'title':'An Overview of MongoDB’},{$set:{'title':’A tutorial on MongoDB'}},{multi:true})

The “save()” method

When this method is used, the existing document is replaced with the new document which has been passed in the “save()” method. The method takes the following syntax:

db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

Consider the example given below:

>db.collection1.save(

{

"_id" : ObjectId(9854548743221adf45bd6), "title":"An Overview of MongoDB", "by":"Lecturer1"

}

)

>db.collection.find()

{ "_id" : ObjectId(9854548745361adf45bd4), "title":"An Overview of MongoDB"}

{ "_id" : ObjectId(9854548768561adf45bd5), "title":"A NOSQL Database"}

{ "_id" : ObjectId(9854548743221adf45bd6), "title":"An overview by Lecturer1"}

>

With the above code, the object with the id “9854548743221adf45bd6” will be replaced with the above example.

Chapter 10- Deletion of a Document

When we want to remove a document from a particular collection in MongoDB, we use the “remove()” method. Note that this method accepts only two parameters. These parameters include the following:

1. Deletion criteria- this parameter is optional. It specifies the criteria for deletion of the document, and this is dependent on the document.

2. justOne- this parameter is also optional. If you set it to 1 or true, then only one document will be removed.

The “remove()” method takes the syntax given below:

db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Consider a collection which has the following documents:

Our aim is to remove all of the documents in the collection whose title is “An Overview of MongoDB.” This can be achieved by use of the example given below:

>db.collection.remove({'title':'An Overview of MongoDB'})

>db.collection.find()

{ "_id" : ObjectId(9854548768561adf45bd5), "title":"A NOSQL Database"}

{ "_id" : ObjectId(9854548743221adf45bd6), "title":"An overview by Lecturer1"}

>

With the above example, the document will be removed from the collection.

Removing a single one

There might be multiple records in your collection. However, you might be interested in deleting only the first record and then leaving the rest untouched. If this is the case, then the parameter “justOne” has to be used in the “remove()”method. This should be used with the following syntx:

db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Removal of all of the Documents

Sometimes, you might not be in need of any document contained in the collection. In this case, you might have to delete all of these documents from the collection. If you need to do this to your collection, then follow the sequence of commands given below:

That is how this can be done.

Chapter 11- Projection in a MongoDB

Projection in MongoDB occurs when only a section of data in a document is selected rather than selecting all of the data contained in a particular document. An example is for a document which has only 10 fields. You might need to select and show only 5 of these fields, and this is an example of projection.

“find()” method

With this method, a second parameter can be accepted which can be used to specify the list of fields that you need to retrieve from the collection. When this method is executed in MongoDB, then it gives all the fields that are contained in the document. To specify the fields which we need to display, we use the values 0 or 1. If you need to show a particular field, then use the value 1 and if you need to hide it, use the value 0. The method takes the syntax given below:

db.COLLECTION_NAME.find({},{KEY:1})

We need to give an example demonstrating how this can be done. Consider a collection named “database1” which has the following data:

{ "_id" : ObjectId(9854548745361adf45bd4), "title":"An Overview of MongoDB"}

{ "_id" : ObjectId(9854548768561adf45bd5), "title":"A NOSQL Database"}

{ "_id" : ObjectId(9854548743221adf45bd6), "title":"An overview by Lecturer1"}

Consider the example given below which will show  the document while we are querying it:

>db.collection1.find({},{"title":1,_id:0})

{"title":"An Overview of MongoDB"}

{"title":"A NoSQL Overview"}

{"title":"An Overview by Lecturer1"}

>

With the “find()” method, the field “_Id” will always be displayed once the method has been executed. If you are not interested in this feature, then the field must be set to zero (0).

Chapter 12- Limiting of Records

The method “limit()” is used when we want to limit records in MongoDB. The method accepts only a single number type argument, and this represents the number of documents which you need to be displayed. The method takes the following syntax:

db.COLLECTION_NAME.find().limit(NUMBER)

Suppose that our collection has the following data:

{ "_id" : ObjectId(9854548745361adf45bd4), "title":"An Overview of MongoDB"}

{ "_id" : ObjectId(9854548768561adf45bd5), "title":"A NOSQL Database"}

{ "_id" : ObjectId(9854548743221adf45bd6), "title":"An overview by Lecturer1"}

We need to display only two documents once we have queried the collection. The following example can be used for this purpose:

>db.collection1.find({},{"title":1,_id:0}).limit(2)

{"title":"MongoDB Overview"}

{"title":"An Overview by Lecturer1"}

>

Note that we have passed the parameter 2 in the “limit()” method, and this acts as a specification of the number of documents which will be displayed after querying the collection. In case we do not pass  any parameter to this method, then all of the documents contained in the collection will be displayed.

The “skip()” method

This method also accepts some arguments specifying the number of documents which are to be displayed, and it can be used for specification of the documents which are to be skipped. The method takes the syntax given below:

db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

Now that our collection has only 3 documents, consider a situation in which we need to display only the third document. In this case, we have to skip the first two documents, and the “skip()” method can be used for this purpose. The example given below can be used to achieve this:

>db.collection1.find({},{"title":1,_id:0}).limit(1).skip(2)

{"title":"An Overview by Lecturer1"}

>

With the example given above, the method will only display the third document in the collection. If no parameter is passed or specified in the method, then the default setting for this method is that it skips 0 items.

Chapter 13- Sorting of Records in MongoDB

Sometimes, you might not be interested in how the documents are arranged in your collection. In this case, you will have to use the “sort()” method so as to sort the elements in the order that you need. In this case, 1 is used for sorting the documents in an ascending order while -1 is used for sorting the elements in a descending order. The method takes the syntax given below:

db.COLLECTION_NAME.find().sort({KEY:1})

Suppose that we have a collection named “collection1” which has the following data:

{ "_id" : ObjectId(9854548745361adf45bd4), "title":"An Overview of MongoDB"}

{ "_id" : ObjectId(9854548768561adf45bd5), "title":"A NOSQL Database"}

{ "_id" : ObjectId(9854548743221adf45bd6), "title":"An overview by Lecturer1"}

We need to use the title of the documents so as to sort them in an ascending order. The following example illustrates how this can be done:

>db.collection1.find({},{"title":1,_id:0}).sort({"title":1})

{"title":"An Overview by Leturer1"}

{"title":"A NoSQL Overview"}

{"title":"An Overview of MongoDB "}

>

Note that in the above example, we have used 1 as the criteria for sorting. This is an indication that the documents will be sorted in an ascending order. If the criteria for sorting is not specified, then the elements will be sorted in an ascending order, as this is the default setting. If we need them to be sorted in a descending order, then we should replace the 1 with a -1.

Chapter 14- Aggregation in MongoDB

With aggregation, the documents are processed, and then the result is returned. With the aggregation operation, values which belong to different documents are grouped together into a single document, and then the operations are performed on the grouped data so that a single result is returned to the user. To perform this grouping operation, we use the “aggregate()” method which takes the following syntax:

db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

Suppose that we have a collection which has the following data:

{

title: 'Introduction,

description: ‘An introduction to the MongoDB database’,

by: ‘Lecturer 1’,

url: 'http://www.lecturer1.com',

tags: ['MongoDB', 'database', 'NoSQL'],

likes: 150

},

{

title: 'NoSQL Database body',

description: ‘A description of what the database contains’,

by: 'Lecturer1',

url: 'http://www.lecturer1.com',

tags: ['MongoDB', 'database', 'NoSQL'],

likes: 100,

comments: [

{

user:'student1',

message: 'A very nice lecture',

dateCreated: new Date(2015,08,12,3,45),

like: 50

}

With the above collection, you might be interesting in knowing the number of documents which have been written by each of the users. This can be achieved by use of the “aggregate()” method as shown below:

> db.collection1.aggregate([{$group : {_id : "$user", num_tutorial : {$sum : 1}}}])

{

"result" : [

{

"_id" : "Lecturer 1",

"num_tutorial" : 1

},

{

"_id" : "num1",

"num_tutorial" : 1

}

],

"ok" : 1

}

>

Note that in the example we have just given above, we have used the field “user” so as to group the documents together. Note that we are incrementing the value of the variable “sum” once a new document has been found, and this will let us know the number of documents that a particular user has created.

Chapter 15- Creating a Backup in MongoDB

It is possible for us to create a backup of our data in MongoDB. In this case, we use the command “mongodump,” and then a backup of the database will be created for us. What happens is that the command takes data from the server and then dumps it into a  dump directory. With the options that are available to the user, one is able to limit the amount of data that is being backed up, and be in a position to backup data which is located in a remote server. The command for data backup takes the syntax given below:

Let us demonstrate how the backup process can be done by use of an example:

Begin by starting up your MongoDB server. My assumption is that the MongoDB that you are using is running on the local server. You can then open up your command prompt and then navigate to the bin directory  where the MongoDB has been installed. Once you are in that directory, just type the command “mongodump,” and then hit the “Return” key.

What happens with the above command is that it will connect you to the server which is running at the local server, which is 127.0.0.1, and the port 27017 if this is where the instance of the MongoDB is running at. All the data which is contained in the server will be backed up in the directory “/bin/dump.”  After executing the command, the type of server that you are connected to will be shown as shown in the figure given below:

The “mongodump” command provides some options which it can be used together with. Note that only the data that you have specified will be backed up at the path that you have specified.

Restoration of data in MongoDB

Once we have performed a backup of the data, we might need to restore it. In MongoDB, this can be done by use of the command “mongorestore.” What happens once this command has been executed is that all of the backup data will be restored from the backup directory. The command takes the syntax given below:

Again, the command will show you the server to which it has been connected, as shown in the figure given below:

As shown in the figure, the connection has been established with the local server, from which I am restoring the data.

Chapter 16- Deployment

You need to be aware of how your application will behave in a production environment while you are preparing a MongoDB for deployment purposes. The deployment process needs to be well managed so that we can avoid any frustrations in the production environment. This is why you need to prototype your setup, conduct a load testing, monitor the key metrics, and then make use of the information that you get so that you can scale your setup. Before the deployment, make sure that you understand how each aspect of the system should operate.

For the purpose of monitoring of deployment, MongoDB provides us with some commands which we can use for this purpose. These are discussed below:

Mongostat

When this command is executed, all the instances of MongoDB which are running are checked, and then a counter of the database operations is returned. The counters in this case include the deletes, updates, cursors, inserts, and queries. With this command, you will also be notified whenever you hit a page fault and your lock percentage will be showcased. When you encounter this, just know that you have a performance problem, such as running short of the memory or any other problem.

For you to run this command, you should begin by running an instance of the MongoDB. Open another command prompt, and then navigate to the “bin” folder of where the installation of MongoDB has been done. Once you are there, just execute the command shown below:

This should work effectively.

Mongotop

With this command, the read and write activity of the MongoDB is tracked and reported, and this is done on the basis of a collection. The default setting for this command is that it should return the information after each second. However, one has the choice of altering this setting to what they need.  The read and the write activity should be checked so as to be sure that they match the intention of your application. With this, you will be sure that a moderate number of writes are fired to the database,  a moderate reading is done from the disk, and the set size of your working is not exceeded.

For the command to be executed, an instance of the MongoDB needs to be started first. You then have to open another command prompt, and then navigate to the “bin” folder of the installation of the MongoDB. You can then execute the command as shown below:

If you need to modify the frequency with which information is returned to you, you should add the time after the command. This is shown in the figure given below:

Once you have executed the command given above, then you will be presented with data after every 30 seconds. You can choose the time that you want rather than the 30 seconds. There are also other mechanisms that are in existence, and they can be used for the monitoring of the MongoDB. You can learn how to use these and then use them.

Chapter 17- Text Search in MongoDB

With MongoDB version 2.4 and above, we are able to use text indexes so as to search inside strings. In this case, we are only interested in getting some specific words in the string. Additionally,  stemming techniques are used whereby we identify some stopping words which we use to identify the search words.

How to enable Text Search in MongoDB

For those who are using MongoDB version 2.6 and above, then this feature is enabled by default, so you are lucky. For those who are using previous versions of MongoDB, then they have to enable this feature by use of the code given below:

Creation of a Text Index

Consider the text given below:

{

"collection_text": "A MongoDB book",

"tags": [

"MongoDB",

"book"

]

}

In the above example, we have our tags under the collection. Our aim is to search inside the above example. In this case, we will have to create a text index, and we will then be in a position to perform our search. This can be done as shown below:

db.collection1.ensureIndex({collection_text:"text"})

How to use the Text Index

Note that in the above section, we have created our text index. We then need to use this text index for the purpose of searching. Our aim is to search for the documents which have the word “MongoDB” in their text. This will be done by use of the command given below:

db.collection1.find({$text:{$search:"MongoDB"}})

The above command gives me the following result once it has been executed:

{ "_id" : ObjectId(9854548745361adf45bd4), "title":"An Overview of MongoDB"}

The reason for the above output is because of the presence of the word “MongoDB” in the title. This word formed our search criteria.

For the users of old versions of MongoDB, then use the command given below:

db.collection1.runCommand("text",{search:" MongoDB "})

The criteria for search has a great significance in improvement of the efficiency of search when compared to the normal search.

How to Delete an Index

In this case, we should begin by searching for the text index. If it exists in your system, then use the following command so as to find it:

db.collection1.getIndexes()

The name of the index that you need should be seen after the execution of the above command. To delete it, run the command given below:

db.collection1.dropIndex("collection_text_text")

That is how it can simply be done in MongoDB.

Chapter 18- Regular Expressions in MongoDB

These are used frequently in databases and programming languages so as to search for a particular pattern in a given string. For us to use regular expressions in MongoDB, we do not have to perform any configurations or some specific commands so as to perform the search.

Consider the document structure and its tags given below:

{

"collection_text": "enjoy reading this MongoDB book",

"tags": [

"MongoDB",

"Lecturer1"

]

}

How to use the “regex” expression

We need to search for the posts which contain the word “MongoDB” in their text. The following query can be used for this purpose:

db.collection1.find({post_text:{$regex:"MongoDB"}})

Alternatively, the query can be written as follows:

db.collection1.find({collection_text:/MongoDB/})

With the above two commands, we will achieve the same result, and the difference will only be on how we have implemented them.

Making the “regex” case insensitive

If you need to make the search by the “regex” expression case insensitive, then the option “$options” is used together with the value “$i,” and this makes the expression a case insensitive one. To implement the search for the word “MongoDB,” irrespective of the case in which the word has been written in, then we can do it as follows:

db.colelction1.find({collection_text:{$regex:"MongoDB",$options:"$i"}})

In my case, the following document is one of the results I get from the above command:

{

"_id" : ObjectId("64983d37d876529c10100115"),

"post_text" : "hey! I enjoy using MongoDB",

"tags" : [ "MongoDB" ]

}

What you realize with the above document is that it has the word “MongoDB” written in two different cases.

Using “regex” in Arrays

The concept of using the “regex” expression for searching can be applied to elements in an array. This concept is very useful when we are using tags. Consider a situation where you need to search for posts which have their tags beginning with the word “MongoDB,” then use the command given below:

db.collection1.find({tags:{$regex:"MongoDB"}})

Chapter 19- MongoDB and Java

Java is a programming language, mostly used for the development of standalone applications. It is possible for us to link this programming language together with the MongoDB, in which case, the latter will store needed by the applications which we develop. However, before we can be able to accomplish this, we must ensure that the Java and the MongoDB  JDBC driver have been set up in our system. In this case, we will not explore how to set up Java in our machine, but we will explore the process of setting up the MongoDB JDBC.

Begin by downloading the latest release of the MongoDB JDBC into your machine. The downloaded file will be packaged. The package “mongo.jar” also needs to be included in the classpath.

Establishing a connection to the Database

For you to establish a connection to the database, you have to first create the database, and if MongoDB does not find the database, then it automatically creates a new one. The code for connecting to the database should be as shown below:

import com.MongoDB.DBObject;

import com.MongoDB.MongoException;

import com.MongoDB.MongoClient;

import com.MongoDB.WriteConcern;

import com.MongoDB.ServerAddress;

import com.MongoDB.DBCollection;

import com.MongoDB.DB;

import com.MongoDB.BasicDBObject;

import java.util.Arrays;

import com.MongoDB.DBCursor;

public class MongoJDBC{

public static void main( String args[] ){

try{

// connecting to the mongo server

MongoClient client = new MongoClient( "localhost" , 27017 );

// connecting to the database

DB database = client.getDB( "myDatabase" );

System.out.println("The connection to the database was successful");

boolean authentication = database.authenticate(userName, password);

System.out.println("Authentication: "+authentication);

}catch(Exception ex){

System.err.println( ex.getClass().getName() + ": " + ex.getMessage() );

}

}

}

Just write the code shown above as it is. It is now time for us to compile and then run the code. Once we execute the above program, a database named “myDatabase” will be created. The path in your system can be changed to what you need. Our assumption is that the current version of the JDBC is in your current path. Just open the terminal, and then execute the following commands:

In my case, I get the following result after executing the above commands:

The above output shows that I was successfully connected to the database. In my case, I had no database named “myDatabase,” which shows that the MongoDB automatically created it.

For those who are running Windows on their machines, compile the code by executing the following commands:

If the authentication succeeds, that is, if the username and the password are true,  the value for “authentication” will then be true.

Creation of a Collection

For us to create a collection while in Java, we still use the “createCollection()” method. Consider the code given below which shows how this can be done:

import java.util.Arrays;

import com.MongoDB.MongoException;

import com.MongoDB.DBObject;

import com.MongoDB.DB;

import com.MongoDB.MongoClient;

import com.MongoDB.ServerAddress;

import com.MongoDB.DBCollection;

import com.MongoDB.WriteConcern;

import com.MongoDB.BasicDBObject;

import com.MongoDB.DBCursor;

public class MongoJDBC{

public static void main( String args[] ){

try{

// Connecting to the MongoDB server

MongoClient client = new MongoClient( "localhost" , 27017 );

// connecting to the databases

DB database = client.getDB( "myDatabase" );

System.out.println("Connection to the database was successful");

boolean authentication = database.authenticate(userName, password);

System.out.println("Authentication: "+authentication);

DBCollection collection = database.createCollection("collection");

System.out.println("The collection was created successfully");

}catch(Exception ex){

System.err.println( ex.getClass().getName() + ": " + ex.getMessage() );

}

}

}

After a successful compilation and execution of the above program, the following result will be obtained:

If you get the above output, then just know that your collection has been created successfully.

Selecting a specific collection

To select or get a certain collection from the database, we use a method named “getCollection().” Consider the example program given below which shows how this can be done:

import java.util.Arrays;

import com.MongoDB.DBCursor;

import com.MongoDB.DBObject;

import com.MongoDB.WriteConcern;

import com.MongoDB.ServerAddress;

import com.MongoDB.MongoClient;

import com.MongoDB.DBCollection;

import com.MongoDB.BasicDBObject;

import com.MongoDB.DB;

import com.MongoDB.MongoException;

public class MongoJDBC{

public static void main( String args[] ){

try{

// connecting to the MongoDB server

MongoClient client = new MongoClient( "localhost" , 27017 );

//  connecting to the databases

DB database = client.getDB( "myDatabase" );

System.out.println("Connected to the database successfully");

boolean authentication = database.authenticate(userName, password);

System.out.println("Authentication: "+authentication);

DBCollection collection = database.createCollection("collection");

System.out.println("The collection was created successfully");

DBCollection coll = database.getCollection("collection");

System.out.println("The collection “collection” was selected successfully");

}catch(Exception ex){

System.err.println( ex.getClass().getName() + ": " + ex.getMessage() );

}

}

}

Just compile and then run the above program. The following output will be observed:

Inserting a Document

If we are in Java, and we need to insert a document into the MongoDB, then we use the “insert()” method. Consider the example given below, which shows how this can be done:

import com.MongoDB.MongoException;

import com.MongoDB.MongoClient;

import com.MongoDB.DB;

import java.util.Arrays;

import com.MongoDB.DBCollection;

import com.MongoDB.ServerAddress;

import com.MongoDB.BasicDBObject;

import com.MongoDB.DBObject;

import com.MongoDB.DBCursor;

import com.MongoDB.WriteConcern;

public class MongoJDBC{

public static void main( String args[] ){

try{

// connecting to the MongoDB server

MongoClient client = new MongoClient( "localhost" , 27017 );

// connecting to the the databases

DB database =client.getDB( "myDatabase" );

System.out.println("Connected to the database successfully");

boolean authentication = database.authenticate(userName,password);

System.out.println("Authentication: "+authentication);

DBCollection collection = db.getCollection("collection");

System.out.println("The collection “collection” was selected successfully");

BasicDBObject document = new BasicDBObject("title", "MongoDB").

append("description", "database").

append("likes", 150).

append("url", "http://www.lecturer1.com/MongoDB/").

append("by", "Lecturer");

collection.insert(document);

System.out.println("The document was inserted successfully");

}catch(Exception ex){

System.err.println( ex.getClass().getName() + ": " + ex.getMessage() );

}

}

}

Just compile, and then execute the above program. The following output should be observed:

When you get the output shown above, it will be an indication that the program ran successfully.

Retrieval of Documents

If you need to display all of the documents which are contained in the collection, then you have to use the “find()” method. A cursor must be used for iteration in this case, as the return for the method is a cursor. Consider the example shown below, which shows how this method can be used for this purpose:

import java.util.Arrays;

import com.MongoDB.DB;

import com.MongoDB.DBCollection;

import com.MongoDB.MongoClient;

import com.MongoDB.DBObject;

import com.MongoDB.DBCursor;

import com.MongoDB.BasicDBObject;

import com.MongoDB.ServerAddress;

import com.MongoDB.WriteConcern;

import com.MongoDB.MongoException;

public class MongoJDBC{

public static void main( String args[] ){

try{

// connecting to the MongoDB server

MongoClient client = new MongoClient( "localhost" , 27017 );

// connecting to the the databases

DB database =client.getDB( "myDatabase" );

System.out.println("Connected to the database successfully");

boolean authentication = database.authenticate(userName,password);

System.out.println("Authentication: "+authentication);

DBCollection collection = db.getCollection("collection");

System.out.println("The collection “collection” was selected successfully");

DBCursor cursor = collection.find();

int j = 1;

while (cursor.hasNext()) {

System.out.println("The inserted Document is: "+j);

System.out.println(cursor.next());

j++;

}

}catch(Exception ex){

System.err.println( ex.getClass().getName() + ": " + ex.getMessage() );

}

}

}

Just write and then execute the above program. The following output shall be observed:

Updating a Document

If you need to update a document which is contained in a MongoDB collection, then you have to use the “update()” method. Consider the example given below, which shows how this can be done:

import java.util.Arrays;

import com.MongoDB.BasicDBObject;

import com.MongoDB.WriteConcern;

import com.MongoDB.MongoClient;

import com.MongoDB.DBCursor;

import com.MongoDB.DB;

import com.MongoDB.DBCollection;

import com.MongoDB.DBObject;

import com.MongoDB.MongoException;

import com.MongoDB.ServerAddress;

public class MongoJDBC{

public static void main( String args[] ){

try{

// connecting to the MongoDB server

MongoClient client = new MongoClient( "localhost" , 27017 );

// connecting to the databases

DB database = mongoClient.getDB( "myDatabase" );

System.out.println("Connected to the database successfully");

boolean authentication = database.authenticate(userName,password);

System.out.println("Authentication: "+authentication);

DBCollection collection = db.getCollection("collection");

System.out.println("The collection “collection” was selected successfully");

DBCursor cursor = collection.find();

int j = 1;

while (cursor.hasNext()) {

DBObject uDocument = cursor.next();

uDocument.put("likes","250")

collection1.update(uDocument);

}

System.out.println("The document was updated successfully");

cursor = collection.find();

int j = 1;

while (cursor.hasNext()) {

System.out.println("The updated document is: "+j);

System.out.println(cursor.next());

j++;

}

}catch(Exception ex){

System.err.println( ex.getClass().getName() + ": " + ex.getMessage() );

}

}

}

Just compile the above prom and then observe the result that you get. It should be as follows:

The output shown above shows that the document was successfully updated.

Conclusion

MongoDB is a NoSQL database which is used for the development of relational databases. It is one of the leading NoSQL databases which were developed in the C++ programming language. The table approach provided while developing databases helps the database developers in the development of relational databases. It has schemas, which offer a high degree of dynamism, explaining why they are much liked by developers. MongoDB is a cross-platform application, as it is supported in the various operating systems which are used by database developers. MongoDB is an open-source platform, meaning that one can download and use it for free. The data in MongoDB can easily be integrated with applications. Before beginning to use the MongoDB on your system, you should begin by installing it onto your system. The installation of MongoDB in Windows is very easy, as you just have to download the package and then extract it normally.

The installation of this will then be simple, as you only have to follow some on-screen instructions. In the case of other operating systems such as Linux, you have to be familiar with the terminal commands which are necessary for downloading and then extracting the package. You should place the package in the directory where it is to be installed. MongoDB comes with a default database named “test.” However, you have the choice of creating your own database even more than one. In most cases, MongoDB uses collections inside the database, and this is where we insert our documents. Once the documents have been inserted into a collection, the data contained in the collection can still be updated, or can be deleted. MongoDB can be linked or integrated with programming languages such as Java and PHP. Operations such as insertion, deletion, and updating of documents can then be done from the programming language, rather than directly in MongoDB.

Table of Contents

Introduction

Chapter 1- Definition

Chapter 2- Environmental Setup

Installation of MongoDB in Windows

Installation of MongoDB in Ubuntu

Chapter 3- Creating a Database

Chapter 4- Dropping (Deleting) the Database

Chapter 5- Creation of a Collection

Chapter 6- The “insert()” method

Chapter 7- Dropping (Deleting) a Collection

Chapter 8- Querying the Collection

The “OR” operation in MongoDB

Combination of “AND” and “OR”

Chapter 9- Updating a Document

Chapter 10- Deletion of a Document

Removing a single one

Removal of all of the Documents

Chapter 11- Projection in a MongoDB

Chapter 12- Limiting of Records

Chapter 13- Sorting of Records in MongoDB

Chapter 14- Aggregation in MongoDB

Chapter 15- Creating a Backup in MongoDB

Chapter 16- Deployment

Chapter 17- Text Search in MongoDB

How to enable Text Search in MongoDB

How to Delete an Index

Chapter 18- Regular Expressions in MongoDB

How to use the “regex” expression

Making the “regex” case insensitive

Chapter 19- MongoDB and Java

Creation of a Collection

Selecting a specific collection

Inserting a Document

Retrieval of Documents

Updating a Document

Conclusion