Core Java

MongoDB Tutorial for Beginners

In this example we will try to understand what is MongoDb and explain the basic operations in the NoSql Database.

1. Introduction

MongoDb is a highly scalable, Document based NoSQL Database written in C++. Document based NoSQL databases work on map-like concept of KEY VALUE pairs. The key being uniquely identifiable property like a String, path etc and the value being the Document that is to be saved. Another example of Document based NoSQL is Apache CouchDB.

The one difference in document based database and other key value based NoSQL database is that, the document stored in the form of value also exposes its metadata to the query engine. Hence, we can query the document based on the meta-data of the document saved as values. We will demonstrate this a little latter.

2. Installation

Let’s start with the download and installation of MongoDB. Installation files for MongoDB can be downloaded from here. Install the MongoDB server as per the instructions provided with the installation files.

Fig 1 : MongoDB installation
Fig 1 : MongoDB installation

3. Demonstration

3.1 Start the MongoDB server

To start the server issue the following command from the {MongoDbHome}/Server/{MongoDB-Version}/bin directory:


mongod.exe --dbpath C:\MongoDb\Data

--dbpath option specifies the location of MongoDB repository.

Now that the Database is up and running let’s look at a few basic commands :

3.2 Create a Collection

A collection is what is closest to a RDBMS table. It hosts a number of MongoDBDocuments. Let’s try creating a New Collection :

db.createCollection("person")

Here’s the output :

Fig 2 : Create Collection
Fig 2 : Create Collection

3.3 Insert a Document

The rows in a RDBMS table is what is Document in a MongoDB Collection. However, unlike RDBMS, the Collection need not have fixed columnar data structure. Different documents may have different set of columns. The general syntax to insert a column into a document is :

db.collectionName.insert({type:value});

Let’s try to insert some Documents into the Person collection and checkout the output:

Fig 3 : MongoDb Insert Example
Fig 3 : MongoDb Insert Example

3.4 Update a Document

Let’s update some of the existing documents. General Update Syntax:

db.collectionName.update({{type:value}},{$set:{{type:NewValue}}},{multi:true|false})

Setting the multi to true or false is to indicate if multiple records are to be updated (if matching) or not.

Here’s the output:

Fig 4 : MongoDb Update Example
Fig 4 : MongoDb Update Example

3.5 Delete a Document

Let’s delete some documentsfrom the Person Collection. Here is the syntax for that:

db.collectionName.remove({type:value});

Here’s the output for the same:

Fig 5 : MongoDb Delete Example
Fig 5 : MongoDb Delete Example

3.6 Query a Collection

To display all the documents in the Collection :

db.collectionName.find()

To display the documents based on some matching conditions, like WHERE clause in SQL

db.collectionName.find({type:value});

Here is the sample of a query command :

Fig 6 : MongoDB Query Example
Fig 6 : MongoDB Query Example

Multiple AND conditions can be declared by separating them with , operator.
e.g.:

 db.person.find({'_id':'2','type':'KeyPad'});

Similarly, OR Operator can also be used :

 db.person.find({
$or: [ { '_id':'2' }, { 'type':'random_type' } ]
});

3.7 Logical Operators in MongoDb

In section 3.6 we saw how we can use equal to operator. But in a real application scenario we need more logical operators like less than greater than Not equal to etc when querying a Collection.

Let’s see how we can use those operators:

Not Equal to:

db.person.find({'_id':{$ne:'0'}})

Greater Than:

db.person.find({'_id':{$gt:'0'}})

Less Than:

db.person.find({'_id':{$lt:'0'}})

Greater Than Equal to :

db.person.find({'_id':{$gte:'0'}})

Less Than Equal to:

db.person.find({'_id':{$lte:'0'}})

Here’s a sample output of the Greater than query:

Fig 7 : Logical operator example
Fig 7 : Logical operator example

3.8 Sorting and limiting the Query Results

Let’s see how we can sort and limit the number of records returned by a query same as in SQL. Syntax to Sort records in MongoDB:

db.collectionName.find({type:value}).sort({'column':1|-1});

Here is the screenshot of different ways in which a query result from find() can be sorted or reverse-sorted by passing 1 or -1 respectively:

Fig 8 : MongoDb Sort Example
Fig 8 : MongoDb Sort Example

Syntax to limit number of records returned by a query :

db.collectionName.limit(value);

This will limit the number of records returned by the query to the value passed in the limit() method.

3.9 Drop the Collection

Here the syntax to drop the collection:

db.collectionName.drop();

And the output:

Fig 9 : drop collection example
Fig 9 : drop collection example

4. Conclusion

Here we studied what is MongoDB in brief and the basic operations supported by it.

Chandan Singh

Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button