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
Appending an entry in one to many embedded documents with MongoDB
To append an entry in MongoDB one-to-many embedded documents, use the $push operator which adds new elements to an existing array field without affecting other array elements.
Syntax
db.collection.update(
{ "matchField": "value" },
{ $push: { "arrayField": newDocument } }
);
Create Sample Data
Let us create a collection with documents ?
db.demo253.insertOne({
_id: "101",
isActive: false,
details: [
{
Name: "Chris"
},
{
CountryName: "US"
}
]
});
{ "acknowledged": true, "insertedId": "101" }
Display all documents from the collection ?
db.demo253.find();
{ "_id": "101", "isActive": false, "details": [ { "Name": "Chris" }, { "CountryName": "US" } ] }
Example: Append Entry to Embedded Array
Following is the query to append an entry in one to many embedded documents ?
db.demo253.update(
{ _id: "101" },
{ $push: { details: { Age: 21 } } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display all documents to see the appended entry ?
db.demo253.find();
{ "_id": "101", "isActive": false, "details": [ { "Name": "Chris" }, { "CountryName": "US" }, { "Age": 21 } ] }
Conclusion
The $push operator effectively appends new documents to embedded arrays in MongoDB. It preserves existing array elements while adding new entries at the end, making it ideal for one-to-many relationships.
Advertisements
