Mongodb 在mongo上分组时,如何在字段上使用$max来检索特定键?

Mongodb 在mongo上分组时,如何在字段上使用$max来检索特定键?,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,如何从mongodb检索分组密钥之外的密钥 文件示例: {code: 'x-1', discount_value: 10, type: 1} {code: 'x-2', discount_value: 8, type: 1} {code: 'x-3', discount_value: 5, type: 2} 查询: { $match: { type: 1 } }, { $group: { _id: null discoun

如何从mongodb检索分组密钥之外的密钥

文件示例:

{code: 'x-1', discount_value: 10, type: 1}
{code: 'x-2', discount_value: 8, type: 1}
{code: 'x-3', discount_value: 5, type: 2}
查询:

{
    $match: {
        type: 1
    }
},
{
    $group: {
        _id: null
        discount_value: {$max: '$discount_value'}
    }
}
此查询将从折扣值(10)键和键id中检索最大值,但如果我没有操作来检索这些键,如何检索代码和类型键

目前的结果是:

{_id: null, discount_value: 10}
预期结果:

{_id: null, discount_value: 10, type: 1, code: 'x-1'}

您可以尝试以下查询:

db.collection.aggregate([
  {
    $match: { type: 1 }
  },
  {
    $group: {
      _id: null,
      doc: {
        $max: {
          discount_value: "$discount_value",
          type: "$type",
          code: "$code"
        }
      }
    }
  }
])
我相信它将在字段
折扣值
上获得
$max
,并从
折扣值为max
的文档中获得相应的
类型
&
代码

另一方面,由于您使用
$match
作为第一阶段,我相信您的数据将不足以高效执行
$sort

db.collection.aggregate([
  {
    $match: { type: 1 }
  },
  {
    $sort: { discount_value: -1 } // sort in desc order
  },
  {
    $limit: 1
  }
])
测试:

注意:


在数据库本身而不是操场上测试第一个查询。在第一次查询中,如果您想将
doc
字段作为文档的根,您可以将其用作最后一步。

我恢复了对post的查询,原始查询有嵌套数据,您认为在这种情况下使用排序可以吗?@Rafacioly:嵌套数据是什么意思?我当前的文档是这样的:
{start_at:ISODate,end_at:ISODate,type:1,include:{a:1,b:2},exclude:{a:1:b:2}
..@rafacioly:对子文档字段进行排序也可以,您尝试过这个查询吗?