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
Pushing values into array with multi field set to TRUE?
To push values into arrays across multiple documents in MongoDB, use the $push operator with update() and set the multi field to true. This allows updating all matching documents in a single operation.
Syntax
db.collection.update(
{filter},
{ $push: { arrayField: "value" } },
{ multi: true }
);
Sample Data
db.demo747.insertMany([
{ "CountryName": ["US", "IND"] },
{ "CountryName": ["UK", "US"] },
{ "CountryName": ["UK", "IND"] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5eae6a50a930c785c834e55f"),
ObjectId("5eae6a57a930c785c834e560"),
ObjectId("5eae6a60a930c785c834e561")
]
}
Display Documents
db.demo747.find();
{ "_id": ObjectId("5eae6a50a930c785c834e55f"), "CountryName": ["US", "IND"] }
{ "_id": ObjectId("5eae6a57a930c785c834e560"), "CountryName": ["UK", "US"] }
{ "_id": ObjectId("5eae6a60a930c785c834e561"), "CountryName": ["UK", "IND"] }
Example: Push Value to All Documents
Push "AUS" to the CountryName array in all documents ?
db.demo747.update(
{},
{ $push: { CountryName: "AUS" } },
{ multi: true }
);
WriteResult({ "nMatched": 3, "nUpserted": 0, "nModified": 3 })
Verify Result
db.demo747.find();
{ "_id": ObjectId("5eae6a50a930c785c834e55f"), "CountryName": ["US", "IND", "AUS"] }
{ "_id": ObjectId("5eae6a57a930c785c834e560"), "CountryName": ["UK", "US", "AUS"] }
{ "_id": ObjectId("5eae6a60a930c785c834e561"), "CountryName": ["UK", "IND", "AUS"] }
Key Points
- Empty filter
{}matches all documents in the collection. -
multi: trueensures all matching documents are updated, not just the first one. -
$pushadds the value to the end of each array.
Conclusion
Use $push with multi: true to add values to arrays across multiple documents efficiently. This approach updates all matching documents in a single operation rather than individual updates.
Advertisements
