4

假设我的文档有一个date字段,我想获取聚合中第一个和最后一个出现的文档。使用$groupand $minor $max,很容易自己获取日期,例如:

db.mycollection.aggregate([
  { $group: {
      _id: 1, // for the example say I'm grouping them all ... 
      first: { $min: "$date" },
      result: { $push: { ... } } // ... and returning them all
  }}
])

这将返回如下结果:

{ _id: 1, first: ISODate(...), result: [...] }

但我想要的不是第一次约会,而是第一次约会的结果。我将如何使用管道来解决这个问题?

我一直在修改使用$project之后扫描数组以查找具有匹配日期的对象,这似乎可以工作,但我想在我偶然发现不正确的方法之前,我想看看是否有适当的方法来做到这一点.

4

1 回答 1

7

您可以使用$first此处来获取排序集的第一个(http://docs.mongodb.org/manual/reference/aggregation/first/#_S_first):

db.mycollection.aggregate([
  { $group: {
      _id: 1, // for the example say I'm grouping them all ... 
      first: { $first: "$date" },
      result: { $push: { ... } } // ... and returning them all
  }}
])

这也将使您使用索引对 $group 进行排序,从而提高性能。

于 2013-02-01T21:12:40.563 回答