How to add a field with specific datatype (list, object) in an existing MongoDB document?

MongoDBDatabaseBig Data Analytics

You can use $set. Let us create a collection with documents −

> db.demo732.insertOne({_id:1,Language:"English"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo732.insertOne({_id:2,Language:"Hindi"});
{ "acknowledged" : true, "insertedId" : 2 }

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

> db.demo732.find();

This will produce the following output −

{ "_id" : 1, "Language" : "English" }
{ "_id" : 2, "Language" : "Hindi" }

Following is the query to add a field with specific datatype (list, object) in an existing MongoDB document −

> db.demo732.update({_id:1},
... { $set:{details:{'subjectName':"MongoDB"}, studentDetails:[{Name:"David"},{CountryName:"US"}]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo732.find();

This will produce the following output −

{ "_id" : 1, "Language" : "English", "details" : { "subjectName" : "MongoDB" }, "studentDetails" : [ { "Name" : "David" }, { "CountryName" : "US" } ] }
{ "_id" : 2, "Language" : "Hindi" }
raja
Published on 15-May-2020 12:53:21
Advertisements