To push elements to an existing array, use $addToSet operator along with update(). Let us first create a collection with documents −
> db.pushElements.insertOne({"Comments":["Good","Awesome","Nice"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd682597924bb85b3f48953")
}Following is the query to display all documents from a collection with the help of find() method −
> db.pushElements.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd682597924bb85b3f48953"),
"Comments" : [
"Good",
"Awesome",
"Nice"
]
}Following is the query to push elements to an existing array in MongoDB −
> db.pushElements.update(
{_id:ObjectId("5cd682597924bb85b3f48953")},
{ "$addToSet":{"Comments":"Cool"} },
upsert=true
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })Let us check the document once again −
> db.pushElements.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd682597924bb85b3f48953"),
"Comments" : [
"Good",
"Awesome",
"Nice",
"Cool"
]
}