MongoDB Update Document

In this post, we will see how to update an existing document in MongoDB.
This page uses the following mongo shell methods:
db.collection.updateOne(<filter>, <update>, <options>)
db.collection.updateMany(<filter>, <update>, <options>)
db.collection.replaceOne(<filter>, <update>, <options>)
The examples on this page use the posts collection. To create and/or populate the posts collection, run the following:
db.posts.insertMany([
   {
      title: 'MongoDB Overview', 
      description: 'MongoDB is no sql database',
      by: 'Java Guides',
      url: 'https://javaguides.net',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 100
   },
 
   {
      title: 'NoSQL Database', 
      description: "NoSQL database doesn't have tables",
       by: 'Java Guides',
      url: 'https://javaguides.net',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 20, 
      comments: [ 
         {
            user:'user1',
            message: 'My first comment',
            dateCreated: new Date(2013,11,10,2,35),
            like: 0 
         }
      ]
   }
]);

{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5e18246f7695f4d696a05985"),
                ObjectId("5e18246f7695f4d696a05986")
        ]
}

Update Documents in a Collection

To update a document, MongoDB provides update operators, such as $set, to modify field values.
To use the update operators, pass to the update methods an update document of the form:
{
  <update operator>: { <field1>: <value1>, ... },
  <update operator>: { <field2>: <value2>, ... },
  ...
}
Some update operators, such as $set, will create the field if the field does not exist.

Update a Single Document

The following example uses db.collection.updateOne() method on the posts collection to update the first document where title equals "MongoDB Overview":
db.posts.updateOne(
   { title : "MongoDB Overview" },
   {
     $set: { "by": "Ramesh", description: "MongoDB is no sql database and document oriented database" }
   }
)
The update operation uses the $set operator to update the value of the by field to "Ramesh" and the value of the description field to "MongoDB is no sql database and document oriented database".

Update Multiple Documents

The following example uses the db.collection.updateMany() method on the posts collection to update all documents where by field equal to ""https://javaguides.net":
db.posts.updateMany(
   { "likes": { $lt: 50 } },
   {
     $set: { "title": "MongoDB NoSQL Database" }
   }
);

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Replace a Document

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to db.collection.replaceOne().
The following example replaces the first document from the inventory collection where by: "Ramesh":
db.posts.replaceOne(
   { by: "Ramesh" },
   {
        "title" : "MongoDB Architecture",
        "description" : "MongoDB Architecture",
        "by" : "Ramesh",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100,
        "lastModified" : ISODate("2020-01-10T09:26:39.709Z")
   }
)
Here is the complete example:
> db.posts.replaceOne(
    { by: "Ramesh" },
    {
         "title" : "MongoDB Architecture",
         "description" : "MongoDB Architecture",
         "by" : "Ramesh",
         "url" : "https://javaguides.net",
         "tags" : [
                 "mongodb",
                 "database",
                 "NoSQL"
         ],
         "likes" : 100,
         "lastModified" : ISODate("2020-01-10T09:26:39.709Z")
    }
 );
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.posts.find().pretty();
{
        "_id" : ObjectId("5e1840697695f4d696a05987"),
        "title" : "MongoDB Architecture",
        "description" : "MongoDB Architecture",
        "by" : "Ramesh",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100,
        "lastModified" : ISODate("2020-01-10T09:26:39.709Z")
}
{
        "_id" : ObjectId("5e1840697695f4d696a05988"),
        "title" : "MongoDB NoSQL Database",
        "description" : "NoSQL database doesn't have tables",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}


Comments