Web Programming TutorialsLearn how to Update, Save and Remove Methods in MongoDB

Learn how to Update, Save and Remove Methods in MongoDB

methods

In this chapter, we are going to explore update, save and remove methods in MongoDB. We are going to gain more interest as we progress further in this MongoDB tutorial series.

Update Method
In MongoDB, the ‘update ()’ and ‘save ()’ methods are used to update the document into a collection. The ‘update ()’ method is used to update the values present in the existing document whereas ‘save ()’ method replaces the entire existing document with the new document which is passed in the ‘save ()’ method.

The following is the basic syntax for ‘update ()’ method in the MongoDB.

> db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)

Example
The following is an example on using the ‘update ()’ statement.

> use update_db
switched to db update_db
> db.update_db.save ( { name: 'Aparajita', role: 'Computer Engineer', work: 'banking'})
WriteResult({ "nInserted" : 1 })
> db.update_db.save ( { name: 'Mohit', role: 'Computer Engineer', work: 'homemaker'})
WriteResult({ "nInserted" : 1 })
> db.update_db.find()
{ "_id" : ObjectId("5849cb1f9ed6bd4c60155e98"), "name" : "Aparajita", "role" : "Computer Engineer", "work" : "banking" }
{ "_id" : ObjectId("5849cb2f9ed6bd4c60155e99"), "name" : "Mohit", "role" : "Computer Engineer", "work" : "homemaker" }
> db.update_db.update ( { 'role' : 'Computer Engineer'},{ $set: {'role' : 'Electronics Engineer'} } )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.update_db.find()
{ "_id" : ObjectId("5849cb1f9ed6bd4c60155e98"), "name" : "Aparajita", "role" : "Electronics Engineer", "work" : "banking" }
{ "_id" : ObjectId("5849cb2f9ed6bd4c60155e99"), "name" : "Mohit", "role" : "Computer Engineer", "work" : "homemaker" }
>

Explanation of the code

  • Here, we are using ‘update_db’ collection name of MongoDB.
  • Then, we are using the ‘save ()’ method twice without “_id” field to save two document. Here, MongoDB will assign unique object ids to these two documents automatically.
  • Next, we are using the ‘find ()’ to display the saved records.
  • After that, we are using the ‘update ()’ method to update the ‘role’ field in the document from ‘Computer Engineer’ to ‘Electronics Engineer’. The entire syntax is shown above. This is to be noted that by default, the MongoDB will always update only a single document. If we want to update multiple documents, then we need to set a parameter ‘multi’ to true within the ‘update ()’ method as shown below.
> db.update_db.update ( { 'role' : 'Computer Engineer'},{ $set: {'role' : 'Electronics Engineer'} },{multi : true} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
  • Once a document is updated then we are using ‘find ()’ method to retrieve all the documents along with the updated one from the MongoDB as shown below.

update-method

Save Method
In this section, we are going to discuss on how to insert a document in the MongoDB Collection. We can insert data into the MongoDB collection by using either MongoDB’s ‘insert ()’ or ‘save ()’ method. The following are the syntaxes.

1. Save Method Syntax
The following is the basic syntax for save () command in MongoDB.

> db.COLLECTION_NAME.save(document)

Example
The following is an example on using the save () statement.

C:\Program Files\MongoDB\Server\3.2\bin>mongo.exe
MongoDB shell version: 3.2.10
connecting to: test
> use demo
switched to db demo
> db.demo.save ( { title: 'save Statement',description: 'MongoDB Tutorial2', company: 'Eduonix Learning Inc.'})
WriteResult({ "nInserted" : 1 })
> db.demo.save ( {"_id" : ObjectId("5813eed6e6893b80c9ae5bba"), title: 'save Statement with id', description: 'MongoDB Tutorial save with object id', company: 'Eduonix Learning Inc.'})
WriteResult({
        "nMatched" : 0,
        "nUpserted" : 1,
        "nModified" : 0,
        "_id" : ObjectId("5813eed6e6893b80c9ae5bba")
})
> db.demo.find()
{"_id": ObjectId ("5849c3ea9ed6bd4c60155e95"), "title" : "save Statement", "description" : "MongoDB Tutorial2", "company" : "Eduonix Learning Inc." }
{ "_id" : ObjectId ("5813eed6e6893b80c9ae5bba"), "title" : "save Statement with id", "description" : "MongoDB Tutorial save with object id", "company" : "Eduonix Learning Inc." }
>

Explanation of the code

  • Here, we are using ‘demo’ collection name of MongoDB.
  • Next, we are using the ‘save ()’ method without “_id” field to save a document. Here, MongoDB will assign unique object id to document automatically.
  • Then, we are using the ‘save ()’ method with “_id” field to save a document. Here, MongoDB will save a document with this unique id and in case another document exists in database with this unique id then it will be updated or modified with this new document.
  • Once documents are saved, we have used the ‘find ()’ method to retrieve the saved documents from the MongoDB as shown below.

save-method

2. Insert Method Syntax
The following is the basic syntax for insert () command in MongoDB.

> db.COLLECTION_NAME.insert(document)

Example
The following is an example on using the insert () statement.

> db.test.insert ( { title: 'Insert Statement',description: 'MongoDB Tutorial', company: 'Eduonix Learning Inc.'})
WriteResult({ "nInserted" : 1 })
> db.test.find()
{ "_id" : ObjectId("5813eed6e6893b80c9ae5bba"), "abc" : 100 }
{ "_id" : ObjectId("5814c9b689c20c164089fbe7"), "title" : "Insert Statement", "description" : "MongoDB Tutorial", "company" : "Eduonix Learning Inc." }
>

Explanation of the code

  • Here, we are using the default ‘test’ collection name of MongoDB.
  • We are issuing an insert command without specifying the _id parameter. In such a case MongoDB will generate a unique ObjectId for this document with three fields i.e. title, description and company.
  • _id parameter is a 12 bytes hexadecimal number unique assigned to every document in a MongoDB collection. This is how these 12 bytes are divided as follows:
_id: ObjectId(4 bytes are timestamp, 3 bytes are machine id, 2 bytes are process id, and 3 bytes are incrementer)

Note: – We can insert multiple documents in a single query by using an array of documents inside an ‘insert ()’ command.

> db.test.save ( [ { title: 'Array1', description: 'Mongo1', company: 'Eduonoix', tags: ['abc','def','ijk'] }, {title: 'Array2', description: 'Mongo2', company: 'Edunoix', tags: ['123', '456', '789'] } ] )
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
>

insert-method

Differences between Save and Insert Methods
The ‘save ()’ method works in a similar way as that of an ‘insert ()’ method when we do not specify _id in the document. If we specify a _id then the ‘save ()’ method will replace the whole data of the document containing _id (i.e. modifying the existing record) as given in ‘save ()’ method.

Remove Method
In MongoDB, the ‘remove ()’ method is used to delete or remove a document from the collection. The ‘remove ()’ method accepts two parameters i.e. the deletion criteria and just one flag as described below.

  • Deletion criteria  it is an optional parameter. When provided, it will delete a document from the collection which is matching the criteria.
  • JustOne  it is an optional parameter. When set to true or 1, then it will remove only one document from the collection.
  • The following is the basic syntax for insert () command in MongoDB.

Syntax:

> db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Example:
The following is an example on using the remove () statement. Consider a collection which has the following three records.

> use update_db
switched to db update_db
> db.update_db.find()
{ "_id" : ObjectId("5849cb1f9ed6bd4c60155e98"), "name" : "Aparajita", "role" : "Electronics Engineer", "work" : "banking" }
{ "_id" : ObjectId("5849cb2f9ed6bd4c60155e99"), "name" : "Mohit", "role" : "Computer Engineer", "work" : "homemaker" }
{ "_id" : ObjectId("5849d0e09ed6bd4c60155e9b"), "name" : "Anmol", "role" : "Student", "work" : "helper" }
>cription" : "MongoDB Tutorial", "company" : "Eduonix Learning Inc." }
>

Case 1: – We want to remove a selective record with ‘role: Student’ from the collection then the following will be the command as shown below.

> db.update_db.remove ( {'role' : 'Student' })
WriteResult({ "nRemoved" : 1 })
> db.update_db.find()
{ "_id" : ObjectId("5849cb1f9ed6bd4c60155e98"), "name" : "Aparajita", "role" : "Electronics Engineer", "work" : "banking" }
{ "_id" : ObjectId("5849cb2f9ed6bd4c60155e99"), "name" : "Mohit", "role" : "Computer Engineer", "work" : "homemaker" }
>

After executing the ‘update ()’ method with criteria to remove ‘role: Student’ we can display and see that the matching criteria document has been removed from the collection.

Case 2: – There are multiple records in a collection and we just want to delete only the first record, then we need to set justOne parameter in ‘remove ()’ method as shown below.
Syntax:

> db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Example

> db.update_db.find()
{ "_id" : ObjectId("5849cb1f9ed6bd4c60155e98"), "name" : "Aparajita", "role" : "Electronics Engineer", "work" : "banking" }
{ "_id" : ObjectId("5849cb2f9ed6bd4c60155e99"), "name" : "Mohit", "role" : "Computer Engineer", "work" : "homemaker" }
> db.update_db.remove ( {'work' : 'banking' }, 1)
WriteResult({ "nRemoved" : 1 })
> db.update_db.find()
{ "_id" : ObjectId("5849cb2f9ed6bd4c60155e99"), "name" : "Mohit", "role" : "Computer Engineer", "work" : "homemaker" }
>

remove-method

Conclusion:
In this chapter, we have learnt about the practical use of update, save, and remove methods with the help of numerous examples.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -