Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Cannot push into an array from MongoDB?
To push into an array with MongoDB, use the $push operator. This operator adds a new element to the end of an existing array field in a document.
Syntax
db.collection.update(
{ <query> },
{ $push: { <arrayField>: <value> } }
);
Sample Data
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();
{
"_id": ObjectId("5e78f099bbc41e36cc3caec2"),
"ListOfFriends": [
"Robert",
"Mike",
"Sam",
"Carol",
"David",
"Mike"
]
}
Example: Push Element to Array
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 })
Verify Result
Display all documents from a collection with the help of find() method ?
db.demo445.find().pretty();
{
"_id": ObjectId("5e78f099bbc41e36cc3caec2"),
"ListOfFriends": [
"Robert",
"Mike",
"Sam",
"Carol",
"David",
"Mike",
"Chris Brown"
]
}
Conclusion
The $push operator successfully adds new elements to arrays in MongoDB documents. It appends values to the end of the specified array field without affecting existing elements.
Advertisements
