> db.c5.find()
{ "_id" : 1, "ary" : [ 2, 3 ] }
> db.c5.update({_id:1},{$push:{ary:{$each:[1,2,3],$slice:-0}}})
> db.c5.find()
{ "_id" : 1, "ary" : [ ] }
> db.c5.update({_id:1},{$push:{ary:{$each:[1,2,3],$slice:-2}}})
> db.c5.find()
{ "_id" : 1, "ary" : [ 2, 3 ] }
$sort
语法:db.collection.update(
{ $push:{
$each: [
...
],
$slice:
$sort:
}
}
}
)
$sort将数组中的元素按照一定的规则进行排序,同样1表示正序,-1表示倒序。
$sort必须与$push、$each结合使用,并且$each值的数组中的元素都必须为对象。
> db.c5.find()
{ "_id" : 1, "ary" : [ ] }
>db.c5.update({_id:1},{$push:{ary:{$each:[{_id:1,score:3},{_id:2,score:5},{_id:3,score:1}],$slice:-5,$sort:{score:-1}}}})
> db.c5.find()
{ "_id" : 1, "ary" : [ { "_id" : 2,"score" : 5 }, {"_id" : 1, "score" : 3 }, {"_id" : 3, "score" : 1 } ] }