Updating a MongoDB document and adding new keys only in the first document?

MongoDBDatabaseBig Data Analytics

This can be easily achieved using MongoDB update(). Let us create a collection with documents −

> db.demo162.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3684359e4f06af551997c2")
}
> db.demo162.insertOne({"StudentName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3684389e4f06af551997c3")
}
> db.demo162.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e36843c9e4f06af551997c4")
}

Display all documents from a collection with the help of find() method −

> db.demo162.find();

This will produce the following output −

{ "_id" : ObjectId("5e3684359e4f06af551997c2"), "StudentName" : "Chris", "StudentAge" : 23 }
{ "_id" : ObjectId("5e3684389e4f06af551997c3"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e36843c9e4f06af551997c4"), "StudentName" : "David" }

Here is the query to update a document, adding new keys in first document −

> db.demo162.update({},{$set:{"StudentAge":23}},{upsert:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo162.find();

This will produce the following output −

{ "_id" : ObjectId("5e3684359e4f06af551997c2"), "StudentName" : "Chris", "StudentAge" : 23 }
{ "_id" : ObjectId("5e3684389e4f06af551997c3"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e36843c9e4f06af551997c4"), "StudentName" : "David" }
raja
Published on 01-Apr-2020 15:19:27
Advertisements