MongoDB Tutorial for beginners

Why MongoDB ?

MongoDB (from humongous) is a cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.

MongoDB provides below features:

  • Document Database
    • Documents (objects) map nicely to programming language data types.
    • Embedded documents and arrays reduce need for joins.
    • Dynamic schema makes polymorphism easier.
  • High Performance
    • Embedding makes reads and writes fast.
    • Indexes can include keys from embedded documents and arrays.
    • Optional streaming writes (no acknowledgments).
  • High Availability
    • Replicated servers with automatic master failover.
  • Easy Scalability
    • Automatic sharding distributes collection data across machines.
    • Eventually-consistent reads can be distributed over replicated servers.
  • Advanced Operations

Installing MongoDB 

Visit official mongoDB website https://www.mongodb.org/ and click on download button and select operating system to download for. We will here download for windows 7 platform and setup.

1_download

Install MongoDB for Windows.

In Windows Explorer, locate the downloaded MongoDB .msi file, which typically is located in the default Downloads folder. Double-click the .msi file. A set of screens will appear to guide you through the installation process.

You may specify an installation directory if you choose the “Custom” installation option.

These instructions assume that you have installed MongoDB to C:\mongodb.

Set up the MongoDB environment.

To start a MongoDB instance using this configuration file, issue a command in the following form:

mongod --config C:/mongodb/mongo.conf
mongod -f C:/mongodb/mongo.conf

Modify the values in the mongod.conf file on your system to control the configuration of your database instance.

 mongo.conf
##store data here
dbpath=C:\mongodb\data

##all output go here
logpath=C:\mongodb\log\mongo.log

##log read and write operations or  verbose level logging
diaglog=3

dbpath is config where our data files are saved.

logpath is config where logs are created.

Now Run MongoDB service by writing in cmd where config is location of the mongo.config file

C:\Program Files\MongoDB\Server\3.0\bin>mongod --config C:\mongodb\mongo.config

Now mongoD service is up. Now we can connect to mongo console by using mongo.exe

C:\Program Files\MongoDB\Server\3.0\bin>mongo

When you connect to mongo then by default db selected is test. You can change the db using use command.

> use mydb
switched to db mydb

Inserting documents 

 db.collection.insert()

Inserts a document or documents into a collection.

The insert() method has the following syntax:

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

Here we will insert products in form of json. Since documents don’t have any specific structure we can directly inserty usin command below.

 > db.products.insert({"name": "SILVER NITRATE",
 "description": "Curabitur convallis.",
 "category": "Argentum Nitricum Kit Refill",
 "price": 5.12,
 "images": "https://assets.entrepreneur.com/content/16x9/822/201503032306
04-trifecta-triangle-selling-products.jpeg"
 });
WriteResult({ "nInserted" : 1 })
>

We can confirm that products has been inserted by query for all products.

For query operations, MongoDB provides a db.collection.find() method. The method accepts both the query criteria and projections and returns a cursor to the matching documents. You can optionally modify the query to impose limits, skips, and sort orders.

> db.products.find()
{ "_id" : ObjectId("560c25e711cfe572863303a9"), "name" : "SILVER NITRATE", "desc
ription" : "Curabitur convallis.", "category" : "Argentum Nitricum Kit Refill",
"price" : 5.12, "images" : "https://assets.entrepreneur.com/content/16x9/822/
20150303230604-trifecta-triangle-selling-products.jpeg" }
>

Note: A default _id field is added to each document which is unique and is indexed by mongo automatically.

The following diagram highlights the components of a MongoDB query operation:

crud-annotated-mongodb-find

The next diagram shows the same query in SQL:

crud-annotated-sql-select

EXAMPLE

> db.products.find( { price: { $gt: 5 } }, { name: 1, price: 1 } ).limit(5)

{ "_id" : ObjectId("560c3424f2924ebfac8bb947"), "name" : "Apis Mellifica, Arnica
 Montana, Calcarea Carbonica, Fucus Vesiculosus, Gambogia, Hepar Suis, Phosphori
cum Acidum, Pituitaria Glandula, Thuja Occidentalis, Thyroidinum Suis,", "price"
 : 38 }
{ "_id" : ObjectId("560c3424f2924ebfac8bb948"), "name" : "Antimonium tartaricum,
 Bromium, Bryonia, Carbo vegetabilis, Carduus marianus, Echinacea purpurea, Hepa
r sulphuris calcareum, Kali bichromicum, Lobelia inflata, Phosphorus, Phytolacca
 decandra, Silicea, Solidago virgaurea, Spongia tosta, Sulphur iodatum", "price"
 : 45 }
{ "_id" : ObjectId("560c3424f2924ebfac8bb949"), "name" : "Malt", "price" : 91 }
{ "_id" : ObjectId("560c3424f2924ebfac8bb94a"), "name" : "cultivated mushroom",
"price" : 24 }
{ "_id" : ObjectId("560c3424f2924ebfac8bb94b"), "name" : "Cefadroxil", "price" :
 50 }

Deleting documents:

db.collection.remove()
Removes documents from a collection.

The db.collection.remove() method can have one of two syntaxes. The remove() method can take a query document and an optional justOne boolean:

db.collection.remove(
   <query>,
   <justOne>
)

Or the method can take a query document and an optional remove options document:

db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }
)

Examples

The following are examples of the remove() method.

Remove All Documents from a Collection

To remove all documents in a collection, call the remove method with an empty query document {}. The following operation deletes all documents from the products collection

db.products.remove( { } )

This operation is not equivalent to the drop() method.

To remove all documents from a collection, it may be more efficient to use the drop() method to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes.

Remove All Documents that Match a Condition

To remove the documents that match a deletion criteria, call the remove() method with the <query>parameter:

The following operation removes all the documents from the collection products where qty is greater than20:

db.products.remove( { price: { $gt: 20 } } )

Remove a Single Document that Matches a Condition

To remove the first document that match a deletion criteria, call the remove method with the query criteria and the justOne parameter set to true or 1.

The following operation removes the first document from the collection products where qty is greater than20:

db.products.remove( { name : "Laptop"  }, true )

End

Leave a comment