MongoDB Insert Update Delete Document Tutorial

MongoDB Insert Update Delete Document Tutorial from Coding Compiler. In this insert document in MongoDB tutorial, we will discuss how to insert a document and how to update and delete a document in MongoDB. Let’s start learning MongoDB.

MongoDB Insert Document Tutorial

In this MongoDB tutorial, we will show you how to insert data into a collection of MongoDB.

The data structure of the document is basically the same as JSON.

All data stored in the collection is in BSON format.

BSON is a binary form storage class of class json, referred to as Binary JSON.

What is a document in MongoDB?

MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents, though it contains more data types than JSON.

Can we store images in MongoDB?

If the images are very small you could Base64 encode them and save the string to the database. You can use the bin data type if you are using any scripting language to store files/images in MongoDB. Bin data is developed to store small size of files.

MongoDB Insert Document

MongoDB uses the insert() or save() methods to insert a document into a collection with the following syntax:

db.COLLECTION_NAME.insert(document)

Instance

The following documents can be stored in the col collection of MongoDB’s runoob database:

> db . col . insert ({ title : 'MongoDB tutorial' ,  
    description : 'MongoDB is a Nosql database' , by : 'novice tutorial ' , 
    url : 'https://codingcompiler.com ' , 
    tags : [ ' Mongodb' , 'database' , 'NoSQL' ], 
    likes : 100 })  
          

In the above example, col is our collection name. If the collection is not in the database, MongoDB will automatically create the collection and insert the document.

View the inserted document:

> db.col.find()
{ "_id" : ObjectId("56064886ade2f21f36b03134"), "title" : "MongoDB tutorial", "description" : "MongoDB is a Nosql database", "by" : "novice tutorial", "url" : "https://codingcompiler.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
>

We can also define the data as a variable as follows:

> document =({ title : 'MongoDB tutorial' ,  
    description : 'MongoDB is a Nosql database' , by : 'novice tutorial' , 
    url : 'https://codingcompiler.com' , 
    tags : [ 'mongodb' , 'database' , 'NoSQL' ], 
    likes : 100 });  
          

After execution, the results are as follows:

{
        "title" : "MongoDB tutorial",
        "description" : "MongoDB is a Nosql database",
        "by" : "novice",
        "url" : "https://codingcompiler.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}

Perform an insert operation:

> db.col.insert(document)
WriteResult({ "nInserted" : 1 })
>

You can also use the db.col.save(document) command to insert a document. If you do not specify the _id field, the save() method is similar to the insert() method. If the _id field is specified, the data for that _id is updated.

There are also several syntaxes for inserting documents after the 3.2 version:

  •  db.collection.insertOne(): insert a document data into the specified collection
  •  db.collection.insertMany(): insert multiple document data into the specified collection
# Insert a single piece of data

> var document = db.collection.insertOne({"a": 3})
> document
{
        "acknowledged" : true,
        "insertedId" : ObjectId("571a218011a82a1d94c02333")
}

#  Inserting multiple data
> var res = db.collection.insertMany([{"b": 3}, {'c': 4}])
> res
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("571a22a911a82a1d94c02337"),
                ObjectId("571a22a911a82a1d94c02338")
        ]
}

 

MongoDB Update Document Tutorial

MongoDB uses the update() and save() methods to update the documents in the collection. Let’s take a closer look at the application of the next two functions and their differences.

  • update()
  • save()

update () method

The update() method is used to update an existing document. The syntax is as follows:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

Parameter Description:

  • Query : query update, similar to the back where within sql update query.
  • Update : update object and some updated operators (such as $, $inc…), etc., can also be understood as the sql update query behind the set
  • Upsert : Optional, the meaning of this parameter is, if there is no update record, whether to insert objNew, true is insert, the default is false, not inserted.
  • Multi : Optional, mongodb defaults to false, only updates the first record found. If this parameter is true, it will check all the records by condition.
  • writeConcern : Optional, throws the level of the exception.

Instance

We insert the following data in the collection col:

> db . col . insert ({ 
    title : 'MongoDB tutorial' ,  
    description : 'MongoDB is a Nosql database' , by : 'novice tutorial ' , 
    url : 'https://codingcompiler.com ' , 
    tags : [ ' Mongodb' , 'database' , 'NoSQL' ], 
    likes : 100 })  
          

Then we update the title by the update() method:

>db.col.update({'title':'MongoDB tutorial'},{$set:{'title':'MongoDB'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })   
> db.col.find().pretty()
{
        "_id" : ObjectId("56064f89ade2f21f36b03136"),
        "title" : "MongoDB",
        "description" : "MongoDB is a Nosql database",
        "by" : "novie tutorial",
        "url" : "https://codingcompiler.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
>

You can see that the title was updated from the original “MongoDB Tutorial” to “MongoDB”.

The above statement will only modify the first found document. If you want to modify multiple identical documents, you need to set the multi parameter to true.

>db.col.update({'title':'MongoDB tutorial'},{$set:{'title':'MongoDB'}},{multi:true})

save() method

The save() method replaces an existing document with the passed in document. The syntax is as follows:

db.collection.save(
   <document>,
   {
     writeConcern: <document>
   }
)

Parameter Description:

  • Document : Document data.
  • writeConcern : Optional, throws the level of the exception.

Instance

In the following example we replaced the document data with _id 56064f89ade2f21f36b03136:

>db.col.save({
    "_id" : ObjectId("56064f89ade2f21f36b03136"),
    "title" : "MongoDB",
    "description" : "MongoDB is a Nosql database",
    "by" : "Runoob",
    "url" : "https://codingcompiler.com",
    "tags" : [
            "mongodb",
            "NoSQL"
    ],
    "likes" : 110
})

After the replacement is successful, we can use the find() command to view the replaced data.

>db.col.find().pretty()
{
        "_id" : ObjectId("56064f89ade2f21f36b03136"),
        "title" : "MongoDB",
        "description" : "MongoDB is a Nosql database",
        "by" : "Runoob",
        "url" : "https://codingcompiler.com",
        "tags" : [
                "mongodb",
                "NoSQL"
        ],
        "likes" : 110
}
>

MongoDb Update Document Examples

Update only the first record:

db.col.update( { “count” : { $gt : 1 } } , { $set : { “test2” : “OK”} } );

Update all:

db.col.update( { “count” : { $gt : 3 } } , { $set : { “test2” : “OK”} },false,true );

Just add the first one:

db.col.update( { “count” : { $gt : 4 } } , { $set : { “test5” : “OK”} },true,false );

Add all added:

db.col.update( { “count” : { $gt : 5 } } , { $set : { “test5” : “OK”} },true,true );

Update all:

db.col.update( { “count” : { $gt : 15 } } , { $inc : { “count” : 1} },false,true );

Update only the first record:

db.col.update( { “count” : { $gt : 10 } } , { $inc : { “count” : 1} },false,false );

MongoDB Delete Document Tutorial

In the previous sections, we have learned how to add data and update data to a collection in MongoDB. In this chapter, we will continue to learn about the removal of MongoDB collections.

The MongoDB remove() function is used to remove data from the collection.

MongoDB data updates can use the update() function. It is a good habit to execute the find() command before executing the remove() function to determine if the execution condition is correct.

remove() Syntax 

The basic syntax of the remove() method is as follows:

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

If your MongoDB is after version 2.6, the syntax is as follows:

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

Parameter Description:

  • Query : (Optional) The condition of the deleted document.
  • justOne : (Optional) If set to true or 1, only one document will be deleted.
  • writeConcern : (Optional) The level at which the exception is thrown.

Instance

In the following document we perform two inserts:

> db . col . insert ({ title : 'MongoDB tutorial' ,  
    description : 'MongoDB is a Nosql database' , by : 'novice tutorial ' , 
    url : 'https://codingcompiler.com ' , 
    tags : [ ' Mongodb' , 'database' , 'NoSQL' ], 
    likes : 100 })  
          

Use the find() function to query the data:

> db.col.find()
{ "_id" : ObjectId("56066169ade2f21f36b03137"), "title" : "MongoDB tutorial", "description" : "MongoDB is a Nosql database", "by" : "novice tutorials", "url" : "https://codingcompiler.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5606616dade2f21f36b03138"), "title" : "MongoDB tutorial", "description" : "MongoDB is a Nosql database", "by" : "novice tutorial", "url" : "https://codingcompiler.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }

Next we remove the document titled ‘MongoDB Tutorial’:

> db . col . remove ({ 'title' : 'MongoDB tutorial' }) WriteResult ({ "nRemoved" : 2 }) # Deleted two data > db . col . find () ...... # No data
               


If you only want to delete the first found record you can set justOne to 1, as shown below:

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

If you want to delete all the data, you can use the following method (similar to the regular SQL truncate command):

>db.col.remove({})
>db.col.find()
>

Note: 

The remove() method is obsolete, and now the official recommendation is to use the deleteOne() and deleteMany() methods.

For example, delete all documents under the collection:

db.inventory.deleteMany({})

Delete all documents with status equal to A:

db.inventory.deleteMany({ status : "A" })

Delete a document with a status equal to D:

db.inventory.deleteOne( { status: "D" } )

Related MongoDB Tutorials

MongoDB Connections Tutorial

MongoDB Create Database Tutorial

MongoDB Create Collections Tutorial

What is MongoDB Tutorial For Beginners

MongoDB Basics Tutorial

MongoDB Update Tutorial

MongoDB Query Tutorial

MongoDB Data Modelling Tutorial

MongoDB Scenarios

MongoDB Aggregation Tutorial

MongoDB Performance and Tools

What is NoSQL

MongoDB Installation Tutorial

MongoDB Concept Parsing

 

Leave a Comment