Pushing values into array with multi field set to TRUE?

MongoDBDatabaseBig Data Analytics

To push values, use $push along with update() with multi field set to TRUE. Let us create a collection with documents −

> db.demo747.insertOne({"CountryName":["US","IND"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae6a50a930c785c834e55f")
}
> db.demo747.insertOne({"CountryName":["UK","US"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae6a57a930c785c834e560")
}
> db.demo747.insertOne({"CountryName":["UK","IND"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae6a60a930c785c834e561")
}

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

> db.demo747.find();

This will produce the following output −

{ "_id" : ObjectId("5eae6a50a930c785c834e55f"), "CountryName" : [ "US", "IND" ] }
{ "_id" : ObjectId("5eae6a57a930c785c834e560"), "CountryName" : [ "UK", "US" ] }
{ "_id" : ObjectId("5eae6a60a930c785c834e561"), "CountryName" : [ "UK", "IND" ] }

Following is the correct query to implement $push in update() −

> db.demo747.update({},{$push:{CountryName:"AUS"}},{multi:true});
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

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

> db.demo747.find();

This will produce the following output −

{ "_id" : ObjectId("5eae6a50a930c785c834e55f"), "CountryName" : [ "US", "IND", "AUS" ] }
{ "_id" : ObjectId("5eae6a57a930c785c834e560"), "CountryName" : [ "UK", "US", "AUS" ] }
{ "_id" : ObjectId("5eae6a60a930c785c834e561"), "CountryName" : [ "UK", "IND", "AUS" ] }
raja
Published on 30-Jun-2020 11:37:10
Advertisements