MongoDB query to push document into an array

MongoDBDatabaseBig Data Analytics

To push document into an array, use $push along with update(). Let us create a collection with documents −

>db.demo310.insertOne({"Name":"Chris","details":[{"Id":101,"Subject":"MySQL"},{"Id":102,"Subject":"MongoDB"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50cabdf8647eb59e562043")
}

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

> db.demo310.find();

This will produce the following output −

{
   "_id" : ObjectId("5e50cabdf8647eb59e562043"), "Name" : "Chris", "details" : [
      { "Id" : 101, "Subject" : "MySQL" }, { "Id" : 102, "Subject" : "MongoDB" }
   ]
}

Following is the query to push document −

> db.demo310.update({ _id:ObjectId("5e50cabdf8647eb59e562043")},
...{ $push: {"details": {
...   "Id" : 103,
...   "Subject": "Java"
...   }}
...}
...)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo310.find();

This will produce the following output −

{
   "_id" : ObjectId("5e50cabdf8647eb59e562043"), "Name" : "Chris", "details" : [
      { "Id" : 101, "Subject" : "MySQL" }, { "Id" : 102, "Subject" : "MongoDB" },
      { "Id" : 103, "Subject" : "Java" }
   ] 
}
raja
Published on 01-Apr-2020 11:12:29
Advertisements