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 two separate arrays in a document with one update call in MongoDB?
To update two separate arrays in a MongoDB document with a single update call, use the $push operator with multiple field specifications in the update document. This allows you to add values to multiple arrays simultaneously.
Syntax
db.collection.update(
{ "query": "condition" },
{
$push: {
"arrayField1": "value1",
"arrayField2": "value2"
}
}
);
Sample Data
db.twoSeparateArraysDemo.insertMany([
{
"StudentName": "Larry",
"StudentFirstGameScore": [98],
"StudentSecondGameScore": [77]
},
{
"StudentName": "Mike",
"StudentFirstGameScore": [58],
"StudentSecondGameScore": [78]
},
{
"StudentName": "David",
"StudentFirstGameScore": [65],
"StudentSecondGameScore": [67]
}
]);
Display all documents ?
db.twoSeparateArraysDemo.find();
{
"_id": ObjectId("5c9b152815e86fd1496b38b8"),
"StudentName": "Larry",
"StudentFirstGameScore": [98],
"StudentSecondGameScore": [77]
}
{
"_id": ObjectId("5c9b152d15e86fd1496b38b9"),
"StudentName": "Mike",
"StudentFirstGameScore": [58],
"StudentSecondGameScore": [78]
}
{
"_id": ObjectId("5c9b153315e86fd1496b38ba"),
"StudentName": "David",
"StudentFirstGameScore": [65],
"StudentSecondGameScore": [67]
}
Update Two Arrays Simultaneously
Push values to both game score arrays for Mike's document in a single update call ?
db.twoSeparateArraysDemo.update(
{ "_id": ObjectId("5c9b152d15e86fd1496b38b9") },
{
$push: {
"StudentFirstGameScore": 45,
"StudentSecondGameScore": 99
}
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Results
Check the updated document to confirm both arrays were modified ?
db.twoSeparateArraysDemo.find({ "StudentName": "Mike" });
{
"_id": ObjectId("5c9b152d15e86fd1496b38b9"),
"StudentName": "Mike",
"StudentFirstGameScore": [58, 45],
"StudentSecondGameScore": [78, 99]
}
Key Points
- The
$pushoperator can target multiple arrays in a single update operation. - Each field-value pair in the
$pushobject corresponds to one array field being updated. - This approach is more efficient than performing separate update calls for each array.
Conclusion
Use $push with multiple field specifications to update two or more arrays simultaneously in MongoDB. This single operation approach improves performance and maintains data consistency across multiple array modifications.
Advertisements
