Work with $push in MongoDB

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

> db.demo738.insertOne({Subjects:["C","C++"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead696557bb72a10bcf0661")
}
> db.demo738.insertOne({Subjects:["MySQL","PL/SQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead696657bb72a10bcf0662")
}

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

> db.demo738.find();

This will produce the following output −

{ "_id" : ObjectId("5ead696557bb72a10bcf0661"), "Subjects" : [ "C", "C++" ] }
{ "_id" : ObjectId("5ead696657bb72a10bcf0662"), "Subjects" : [ "MySQL", "PL/SQL" ] }

Following is the query to push −

>db.demo738.update({_id:ObjectId("5ead696657bb72a10bcf0662")},{$push:{"Subjects":"MongoDB"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo738.find();

This will produce the following output −

{ "_id" : ObjectId("5ead696557bb72a10bcf0661"), "Subjects" : [ "C", "C++" ] }
{ "_id" : ObjectId("5ead696657bb72a10bcf0662"), "Subjects" : [ "MySQL", "PL/SQL", "MongoDB" ] }
raja
Published on 30-Jun-2020 11:20:47
Advertisements