OPTIONS
翻译或纠错本页面

限制数组元素在更新之后的数量

2.4 新版功能.

简介

考虑一个应用:用户可能会提交许多分数(例如一个测试),但是应用仅仅需要追踪测试分数中的前三个就行了。

这个范例使用包含 $each$sort$slice 修改符的 $push 操作符以排序并且获取一个固定大小的数组。

重要

这个数组的元素必须为文档,以便使用 $sort 修改符。

例子

考虑 students 集合中的下列文档:

{
  _id: 1,
  scores: [
            { attempt: 1, score: 10 },
            { attempt: 2 , score:8 }
          ]
}

下面的更新使用 $push 操作符,包含:

  • the $each modifier to append to the array 2 new elements,
  • the $sort modifier to order the elements by ascending (1) score, and
  • the $slice modifier to keep the last 3 elements of the ordered array.
db.students.update(
                    { _id: 1 },
                    { $push: { scores: { $each : [
                                                   { attempt: 3, score: 7 },
                                                   { attempt: 4, score: 4 }
                                                 ],
                                         $sort: { score: 1 },
                                         $slice: -3
                                       }
                              }
                    }
                  )

注解

当使用 $sort 修饰符在数组元素上的时候,直接访问子文档元素而不是在数组字段上使用 dot notation

在这个操作之后,在 scores 数组里,文档仅仅包含最高的3个分数。

{
   "_id" : 1,
   "scores" : [
                { "attempt" : 3, "score" : 7 },
                { "attempt" : 2, "score" : 8 },
                { "attempt" : 1, "score" : 10 }
              ]
}

参见