CRUD Operations in MongoDB


What is MongoDB ?

Classified as a No SQL database , MongoDB is a scalable, open source, high performance , document-oriented database designed by keeping developers agility in mind. It is document-oriented which means that it does not store data in tables and rows as we would in relational databases like MySQL, In this we store data in JSON-like documents with dynamic schema.

Prerequisites

In order to understand this article , you need to have :

  • MongoDB installed
  • Basic knowledge of MongoDB

Create a Database
In order to create a Database , use command is used.
		        
//use Your_database_name
use demo_db
                
	            

After running you will observe something like this on your MongoDB CLI :
		        
>use demo_db
switched to db demo_db
                
	            

Create a Collection

As we all know , MongoDB is an Document oriented database where data is stored in the form of documents and those documents are further stored in collections. So we can create a collection using the db.createCollection() Method.


		        
//db.createCollection("Name_of_your_collection" , {Options such as Auto-indexing , size , etc }* )
// * denotes that options is an optional field.
>use demo_db
switched to db demo_db
>db.createCollection("democollection")
{ "ok" : 1 }
>
                
	            

We can see the collection created by using the command show collections as shown below :
		        
>show collections
democollection
system.indexes
                
	            

Creating a collection with some options in it is shown below :
		        
>db.createCollection("demoCol", {  autoIndexId : false, size : 61428,capped : true, max : 100 } )
{ "ok" : 1 }
                
	            

Moreover we dont need to create collections in MongoDB because it will be automatically created when we insert some document.
Inserting data in a Document

MongoDB is an Document oriented database where data is stored in the form of documents. So we can insert the data into a document using the insert(document) Method. Its syntax is shown below :


		        
//db.COLLECTION_NAME.insert(document)
>use demo_db
switched to db demo_db
>db.demoCollection.insert([
   {
      Name: 'sophia', 
      Age: 23,
      sex: 'female',
      website: 'https://www.nodejsera.com',
      tags: ['mongodb', 'database', 'NoSQL']
    }
])
                
	            

Inserting multiple documents using insert() command is shown below:
		        
//db.COLLECTION_NAME.insert(document)
>use demo_db
switched to db demo_db
>db.demoCollection.insert([
   {
      Name: 'sophia', 
      Age: 23,
      sex: 'female',
      website: 'https://www.nodejsera.com',
      tags: ['mongodb', 'database', 'NoSQL']
    },
	{
      Name: 'rj', 
      Age: 22,
      sex: 'male',
      website: 'https://www.nodejsera.com',
      tags: ['nodejs', 'gulpjs', 'webdeveloper']
    },
	{
      Name: 'ricky', 
      Age: 25,
      sex: 'male',
      website: 'https://www.nodejsera.com',
      tags: ['pyhton', 'machinelearning', 'expert']
    }
])
	
                
	            

MondoDb will automatically assign each document an unique _id. _id is 12 bytes hexadecimal number unique for every document in a collection. It is generated via keeping the following format in :
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

Querying data from a Document

Now we will see how we can query a document from a collection in MongoDB. So we can query the document of a collection using the find() method. Its syntax is shown below :


		        
//db.COLLECTION_NAME.find()
>use demo_db
switched to db demo_db
>db.demoCollection.find({"name":"sophia"})

{
    "_id": ObjectId(5cf87da9208b),
    "Name": "sophia", 
    "Age": 23,
    "sex": "female",
    "website": "https://www.nodejsera.com",
    "tags": ["mongodb", "database", "NoSQL"]
}
>

                
	            



Operation Syntax Example
Equality {:} db.demo_collection.find({"name":"sophia"})
Less than {:{$lt:}} db.demo_collection.find({"age":{$lt:24}})
greater than {:{$gt:}} db.demo_collection.find({"age":{$gt:22}})
not equals {:{$ne:}} db.demo_collection.find({"age":{$ne:25}})
Less than equals {:{$lte:}} db.demo_collection.find({"age":{$lte:24}})
greater than equals {:{$gte:}} db.demo_collection.find({"age":{$gte:22}})


We can also use and & or which is explained in detail in MongoDB's respective tutorial.

Updating a Document in MongoDB

We can update the document using the update() method. and in some case save() method can also be used to update the document in a collection. the syntax and example for update() is shown below :


		        
//db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
>use demo_db
switched to db demo_db
>db.demo_collection.update({'name':'sophia'},{$set:{'name':'sopia'}})
>db.demo_collection.find()
{
    "_id": ObjectId(5cf87da9208b),
    "Name": "sopia", 
    "Age": 23,
    "sex": "female",
    "website": "https://www.nodejsera.com",
    "tags": ["mongodb", "database", "NoSQL"]
}

>

                
	            

This will only update the first document it will find with the matching criteria but if you want to update all the documents that matches the given criteria then we need to add an attribute in the end which is shown below :

		        
//db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
>use demo_db
switched to db demo_db
>db.demo_collection.update({'name':'sophia'},{$set:{'name':'sopia'}},{multi:true})


                
	            

{multi:true} It will make sure that updation is performed on all the matching documents.


save()
It will replace the existing document completely with a new document. the syntax and example is shown below :
		        
//>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
>use demo_db
switched to db demo_db
>db.demo_collection.save(
{
	'_id': ObjectId(5cf87da9208b)
	'name':'sophia',
	'web' : 'www.nodejsera.com'
})
	


                
	            

Now if you will check this document it consists of this new values instead of the old ones which includes age , sex, etc.
Deleting a Document in MongoDB

We can delete the document using the remove() method. the syntax and example is shown below :


		        
//>db.COLLECTION_NAME.remove(DELETION_CRITERIA)
>use demo_db
switched to db demo_db
>db.demo_collection.remove({'name':'sophia'})

>

                
	            

Deleting just a single document. If there are multiple records matching the criteria and you want to delete just the first one out of it , then we can use this attribute of remove() method. the syntax is shown below :


		        
>db.COLLECTION_NAME.remove(DELETION_CRITERIA ,1)


                
	            

Deleting all the records of the collection. it can be achieved using the following command


		        
>db.COLLECTION_NAME.remove()

                
	            

summary
  • What is MongoDB
  • Prerequisites
  • Create a Database
  • Create a Collection
  • Inserting data in a Document
  • Querying data from a Document
  • Updating a Document in MongoDB
  • Deleting a Document in MongoDB