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
Searching for an array entry via its id in a MongoDB collection and performing update
To search for an array entry via its ID in a MongoDB collection and perform an update, use the positional $ operator along with dot notation. The $ operator identifies the matched array element, allowing you to update specific fields within that element.
Syntax
db.collection.update(
{ "arrayField._id": "targetId" },
{ $set: { "arrayField.$.fieldToUpdate": "newValue" } }
);
Create Sample Data
db.demo49.insertOne({
"Name": "David",
"Details": [
{
"_id": "D1234",
"Subject": "MySQL"
},
{
"_id": "E234",
"Subject": "Java"
},
{
"_id": "F456",
"Subject": "Python"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e270a77cfb11e5c34d89902")
}
Display Current Documents
db.demo49.find();
{
"_id": ObjectId("5e270a77cfb11e5c34d89902"),
"Name": "David",
"Details": [
{ "_id": "D1234", "Subject": "MySQL" },
{ "_id": "E234", "Subject": "Java" },
{ "_id": "F456", "Subject": "Python" }
]
}
Update Array Entry by ID
Update the Subject field for the array element with ID "E234" from "Java" to "MongoDB" :
db.demo49.update(
{ "Details._id": "E234" },
{ $set: { "Details.$.Subject": "MongoDB" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Update Result
db.demo49.find();
{
"_id": ObjectId("5e270a77cfb11e5c34d89902"),
"Name": "David",
"Details": [
{ "_id": "D1234", "Subject": "MySQL" },
{ "_id": "E234", "Subject": "MongoDB" },
{ "_id": "F456", "Subject": "Python" }
]
}
Conclusion
Use Details._id in the query to find the specific array element, then Details.$.Subject with the positional operator to update the matched element. The $ operator automatically identifies which array element matched the query condition.
Advertisements
