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
Push and slice multiple times in MongoDB?
To push and slice multiple times in MongoDB, use the $push operator with $each and $slice modifiers. The $slice operator limits the array size, keeping only the specified number of elements after each push operation.
Syntax
db.collection.update(
{ "field": "value" },
{
"$push": {
"arrayField": {
"$each": ["newElement"],
"$slice": -N
}
}
}
);
Create Sample Data
db.demo656.insertOne({Name: "John"});
{
"acknowledged": true,
"insertedId": ObjectId("5ea060264deddd72997713cf")
}
db.demo656.find();
{ "_id": ObjectId("5ea060264deddd72997713cf"), "Name": "John" }
Example 1: First Push and Slice Operation
Push "John" to the ListOfName array and limit it to the last 9 elements ?
db.demo656.update(
{Name: "John"},
{
"$push": {
"ListOfName": {
"$each": ["John"],
"$slice": -9
}
}
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
db.demo656.find();
{ "_id": ObjectId("5ea060264deddd72997713cf"), "Name": "John", "ListOfName": ["John"] }
Example 2: Second Push and Slice Operation
Push "David" to the same array while maintaining the slice limit ?
db.demo656.update(
{Name: "John"},
{
"$push": {
"ListOfName": {
"$each": ["David"],
"$slice": -9
}
}
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
db.demo656.find();
{ "_id": ObjectId("5ea060264deddd72997713cf"), "Name": "John", "ListOfName": ["John", "David"] }
Key Points
-
$slice: -Nkeeps the last N elements in the array after each push operation. -
$eachallows pushing multiple elements in a single operation. - The slice operation occurs after the push, maintaining the array size limit.
Conclusion
Using $push with $slice enables controlled array growth by automatically limiting array size after each addition. This is useful for maintaining fixed-size arrays like recent activity logs or latest entries.
Advertisements
