How to insert an item to an array that is inside an object in MongoDB?

MongoDBDatabaseBig Data Analytics

To insert an item to an already created array inside an object, use MongoDB $push. Let us create a collection with documents −

> db.demo449.insertOne(
... {
...    details1: {
...       details2: [{
...          _id:new ObjectId(),
...             Name:"Chris"
...       }],
...       details3: [{
...          _id:new ObjectId(),
...          Name:"David"
...       }]
...    }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7a40e971f552a0ebb0a6e3")
}

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

> db.demo449.find();

This will produce the following output −

{ "_id" : ObjectId("5e7a40e971f552a0ebb0a6e3"), "details1" : { "details2" : [ { "_id" :
ObjectId("5e7a40e971f552a0ebb0a6e1"), "Name" : "Chris" } ], "details3" : [ { "_id" :
ObjectId("5e7a40e971f552a0ebb0a6e2"), "Name" : "David" } ] } }

Following is the query to insert an item to an array that is inside an object −

> db.demo449.update({_id:ObjectId("5e7a40e971f552a0ebb0a6e3")}, {$push: {
'details1.details2':{_id:ObjectId(),"Name":"Carol"}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }

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

> db.demo449.find();

This will produce the following output −

{ "_id" : ObjectId("5e7a40e971f552a0ebb0a6e3"), "details1" : { "details2" : [ { "_id" :
ObjectId("5e7a40e971f552a0ebb0a6e1"), "Name" : "Chris" }, { "_id" :
ObjectId("5e7a41a671f552a0ebb0a6e5"), "Name" : "Carol" } ], "details3" : [ { "_id" :
ObjectId("5e7a40e971f552a0ebb0a6e2"), "Name" : "David" } ] } }
raja
Published on 11-May-2020 09:00:17
Advertisements