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 an array using FindAndUpdate()?
To update an array in MongoDB, use the findAndModify() method combined with the $ positional operator to target specific array elements. This method updates the document and returns either the original or updated version.
Syntax
db.collection.findAndModify({
query: { "arrayField": "matchValue" },
update: { $set: { "arrayField.$": "newValue" } }
});
Sample Data
db.demo152.insertMany([
{"id": 102, "Name": ["Chris", "David"], "Score": 45},
{"id": 103, "Name": ["Mike", "Carol"], "Score": 65}
]);
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("5e3515bcfdf09dd6d08539dd"),
"1": ObjectId("5e3515cafdf09dd6d08539de")
}
}
Display all documents from the collection ?
db.demo152.find();
{ "_id": ObjectId("5e3515bcfdf09dd6d08539dd"), "id": 102, "Name": ["Chris", "David"], "Score": 45 }
{ "_id": ObjectId("5e3515cafdf09dd6d08539de"), "id": 103, "Name": ["Mike", "Carol"], "Score": 65 }
Example: Update Array Element
Update "Chris" to "Robert" in the Name array for document with id 102 ?
var result = db.demo152.findAndModify({
query: {
id: 102,
Score: {$lt: 50},
Name: "Chris"
},
update: {
$set: {"Name.$": "Robert"},
$inc: {Score: 20}
}
});
Verify the update ?
db.demo152.find();
{ "_id": ObjectId("5e3515bcfdf09dd6d08539dd"), "id": 102, "Name": ["Robert", "David"], "Score": 65 }
{ "_id": ObjectId("5e3515cafdf09dd6d08539de"), "id": 103, "Name": ["Mike", "Carol"], "Score": 65 }
Key Points
- The
$positional operator updates the first matching array element -
findAndModify()provides atomic update operations - Combine multiple update operations using
$setand$inc
Conclusion
Use findAndModify() with the $ positional operator to update specific array elements atomically. This method ensures precise targeting of array elements while allowing multiple field updates in a single operation.
Advertisements
