mongodb聚合:如何以最小/最大而不是值的形式返回对象 [英] mongodb aggregation: How to return a the object with min/max instead of the value

查看:73
本文介绍了mongodb聚合:如何以最小/最大而不是值的形式返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我的文档有一个date字段,我想获取聚合中出现的第一个和最后一个文档.使用$group$min$max,可以很容易地自己获取日期,例如:

Say my document has a date field, and I want to get the first and last occuring documents in an aggregation. Using $group and $min or $max, it's easy to get the dates themselves, e.g.:

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: [...] }

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

But what I want isn't the first date, but rather the result with the first date. How would I get at this using the pipeline?

我一直在尝试使用$project之后在数组中扫描具有匹配日期的对象,这似乎可行,但我想我会看看是否有适当的的一种方法,在我偶然发现一个不合适的方法之前.

I've been tinkering with using $project to scan the array afterwards for the object with the matching date, which seems like it could work, but I thought I'd see if there was a proper way to do this before I stumbled on an improper one.

推荐答案

您可以在此处使用$first来获取排序后的集合中的第一个(

You can use $first here to be able to get the first of a sorted set ( 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进行排序,从而提高性能.

This will also you to use indexes for sorts on the $group which increases performance.

这篇关于mongodb聚合:如何以最小/最大而不是值的形式返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆