mongodb聚合:如何使用min/max而不是值返回对象

num*_*407 4 mongodb

假设我的文档有一个date字段,我想在聚合中获取第一个和最后一个出现的文档.使用$group$min$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
  }}
])
Run Code Online (Sandbox Code Playgroud)

这将返回如下结果:

{ _id: 1, first: ISODate(...), result: [...] }
Run Code Online (Sandbox Code Playgroud)

但我想要的不是第一次约会,而是第一次约会的结果.我怎样才能使用管道?

我一直在修改$project用于扫描数组之后的具有匹配日期的对象,看起来它可以工作,但我想我会看到是否有一个正确的方法来做到这一点之后我偶然发现了一个不正确的.

Sam*_*aye 6

你可以$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
  }}
])
Run Code Online (Sandbox Code Playgroud)

这也可以使用$ group上的排序索引来提高性能.