Push new key element into subdocument of MongoDB?


You can use $set operator for this. Following is the syntax −

db.yourCollectionName.update({"_id" : yourObjectId },{$set: { "yourOuterFieldName.anyInnerFieldName": yourValue}});

Let us first create a collection with documents −

> db.pushNewKeyDemo.insertOne({"UserId":100,"UserDetails":{}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda58f5b50a6c6dd317adbf")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.pushNewKeyDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cda58f5b50a6c6dd317adbf"), "UserId" : 100, "UserDetails" : { } }

Following is the query to push new key element into subdocument of MongoDB −

> db.pushNewKeyDemo.update({"_id" : ObjectId("5cda58f5b50a6c6dd317adbf")},{$set: {
   "UserDetails.UserName": "David Miller"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the document once again −

> db.pushNewKeyDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cda58f5b50a6c6dd317adbf"), "UserId" : 100, "UserDetails" : { "UserName" : "David Miller" } }

Updated on: 30-Jul-2019

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements