$each $position $sort $slice

$push 向数组中添加元素

$each 循环数据(循环添加数据到数组)

$sort 对数组进行排序(1:升序;-1:降序。)

$slice 对整个collection表进行数据裁减,用的时候一定要当心(固定整个数组最大长度);

    正整数,表示从前面开始,截取长度为3的数组;负整数,表示从后面开始,截取长度为3的数组。

$position 插入数据的位置。($position:2表示从第二个位置后面插入数据)

db.test.insert(
{
 "_id" : 5,
 "quizzes" : [
 { wk: 1, "score" : 10 },
 { wk: 2, "score" : 8 },
 { wk: 3, "score" : 5 },
 { wk: 4, "score" : 6 }
 ]
}
);

db.test.update( { _id: 5 },
 { $push: { quizzes: { $each: [ { wk: 5, score: 8 },
                                { wk: 6, score: 7 },
                                { wk: 7, score: 6 } ],
                       $sort: { score: -1 },
                       $slice: 3,
                       $position:2
                      }
           }
 }
 );


くろさきいちご
原文地址:https://www.cnblogs.com/Andy-Li/p/5881486.html