You can slice the elements of the comments array to the last n
elements (-10
in the example below). Try this in the shell:
db.coll.update(
{ },
{ $push: { comments: { $each: [ ], $slice: -10 } } },
{ multi: true }
)
Since MongoDB 2.6 you can also use a positive n
to update the array to contain only the first n
elements.
In case you have a field you want to sort on before applying the slice
operation:
db.coll.update(
{ }, {
$push: {
comments: {
$each: [ ],
$sort: { <field_to_sort_on>: 1 },
$slice: -10
}
}
},
{ multi: true }
)