Cannot push into an array from MongoDB?

MongoDBDatabaseBig Data Analytics

To push into an array with MongoDB, use $push. Let us create a collection with documents −

> db.demo445.insertOne({"ListOfFriends":["Robert","Mike","Sam","Carol","David","Mike"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78f099bbc41e36cc3caec2")
}

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

> db.demo445.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e78f099bbc41e36cc3caec2"),
   "ListOfFriends" : [
      "Robert",
      "Mike",
      "Sam",
      "Carol",
      "David",
      "Mike"
   ]
}

Following is the query to push into an array −

> db.demo445.update(
...    { _id: ObjectId("5e78f099bbc41e36cc3caec2") },
...    { $push: { ListOfFriends: "Chris Brown" } }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo445.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e78f099bbc41e36cc3caec2"),
   "ListOfFriends" : [
      "Robert",
      "Mike",
      "Sam",
      "Carol",
      "David",
      "Mike",
      "Chris Brown"
   ]
}
raja
Published on 06-Apr-2020 17:04:46
Advertisements