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
MongoDB query to update nested document
To update a nested document in MongoDB, use the $ positional operator with the $set operator. The $ operator identifies the array element that matches the query condition and allows you to update specific fields within that element.
Syntax
db.collection.update(
{"arrayName.field": "matchValue"},
{ $set: { "arrayName.$.field": "newValue" } }
);
Create Sample Data
Let us create a collection with documents ?
db.demo595.insertOne({
"Information": [
{ "_id": new ObjectId(), "Name": "Chris" },
{ "_id": new ObjectId(), "Name": "Robert" }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e93369cfd2d90c177b5bce4")
}
Display Current Documents
Display all documents from a collection with the help of find() method ?
db.demo595.find().pretty();
{
"_id": ObjectId("5e93369cfd2d90c177b5bce4"),
"Information": [
{
"_id": ObjectId("5e93369cfd2d90c177b5bce2"),
"Name": "Chris"
},
{
"_id": ObjectId("5e93369cfd2d90c177b5bce3"),
"Name": "Robert"
}
]
}
Update Nested Document
Following is the query to update nested document ?
db.demo595.update(
{"Information._id": ObjectId("5e93369cfd2d90c177b5bce2")},
{ $set: {"Information.$.Name": "David Miller"} }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display all documents to verify the update ?
db.demo595.find().pretty();
{
"_id": ObjectId("5e93369cfd2d90c177b5bce4"),
"Information": [
{
"_id": ObjectId("5e93369cfd2d90c177b5bce2"),
"Name": "David Miller"
},
{
"_id": ObjectId("5e93369cfd2d90c177b5bce3"),
"Name": "Robert"
}
]
}
Conclusion
Use the $ positional operator with $set to update specific fields within nested array documents. The $ identifies the first array element matching your query condition, allowing precise updates to nested data structures.
Advertisements
