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 array with another field?
To update an array with another field in MongoDB, use the $push operator along with $each to add multiple values at once. The $slice modifier can limit the array size.
Syntax
db.collection.update(
{filter},
{
$push: {
arrayField: {
$each: ["value1", "value2"],
$slice: maxArraySize
}
}
}
);
Sample Data
db.demo283.insertOne({
"Name": "Chris",
"Status": ["Active", "Inactive"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e4ab97ddd099650a5401a75")
}
Display the document to verify initial data ?
db.demo283.find();
{
"_id": ObjectId("5e4ab97ddd099650a5401a75"),
"Name": "Chris",
"Status": ["Active", "Inactive"]
}
Example: Update Array with Multiple Values
Add "Regular" and "NotRegular" to the Status array and limit array size to 4 elements ?
db.demo283.update(
{},
{
$push: {
Status: {
$each: ["Regular", "NotRegular"],
$slice: -4
}
}
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify the updated document ?
db.demo283.find();
{
"_id": ObjectId("5e4ab97ddd099650a5401a75"),
"Name": "Chris",
"Status": ["Active", "Inactive", "Regular", "NotRegular"]
}
Key Points
-
$eachallows adding multiple values to an array in a single operation. -
$slice: -4keeps only the last 4 elements, useful for maintaining array size limits. - Use empty filter
{}to update all documents in the collection.
Conclusion
The $push operator with $each efficiently adds multiple values to arrays. Combine with $slice to control array size and prevent unlimited growth in your MongoDB collections.
Advertisements
