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
Update tag records in MongoDB quickly
To update tag records in MongoDB quickly, use the $ positional operator along with the update command. The $ operator identifies the first array element that matches the query condition and updates it efficiently.
Syntax
db.collection.update(
{ "arrayField.field": "matchValue" },
{ $set: { "arrayField.$.field": "newValue" } }
);
Create Sample Data
Let us create a collection with tag documents ?
db.demo713.insertOne({
tags: [
{
id: 101,
Name: "Tag-1"
},
{
id: 102,
Name: "Tag-3"
},
{
id: 103,
Name: "Tag-3"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ea8625a5d33e20ed1097b87")
}
Display all documents from the collection ?
db.demo713.find();
{
"_id": ObjectId("5ea8625a5d33e20ed1097b87"),
"tags": [
{ "id": 101, "Name": "Tag-1" },
{ "id": 102, "Name": "Tag-3" },
{ "id": 103, "Name": "Tag-3" }
]
}
Update Tag Record
Update the tag with id 102 from "Tag-3" to "Tag-2" ?
db.demo713.update(
{ "tags.id": 102 },
{ $set: { "tags.$.Name": "Tag-2" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display the updated document ?
db.demo713.find().pretty();
{
"_id": ObjectId("5ea8625a5d33e20ed1097b87"),
"tags": [
{
"id": 101,
"Name": "Tag-1"
},
{
"id": 102,
"Name": "Tag-2"
},
{
"id": 103,
"Name": "Tag-3"
}
]
}
Conclusion
The $ positional operator provides an efficient way to update specific elements in arrays by matching query conditions. It updates only the first matching element, making tag record updates quick and precise.
Advertisements
