首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在域上使用$max时,如何在mongo上分组时如何检索特定的键?

在域上使用$max时,如何在mongo上分组时如何检索特定的键?
EN

Stack Overflow用户
提问于 2020-06-03 19:25:32
回答 1查看 106关注 0票数 1

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

文件示例:

代码语言:javascript
复制
{code: 'x-1', discount_value: 10, type: 1}
{code: 'x-2', discount_value: 8, type: 1}
{code: 'x-3', discount_value: 5, type: 2}

查询:

代码语言:javascript
复制
{
    $match: {
        type: 1
    }
},
{
    $group: {
        _id: null
        discount_value: {$max: '$discount_value'}
    }
}

这个查询将从discount_value (10)键和键_id检索最大值,但是如果我没有操作来执行这些键,那么如何检索代码并键入键呢?

目前的结果是:

代码语言:javascript
复制
{_id: null, discount_value: 10}

预期结果:

代码语言:javascript
复制
{_id: null, discount_value: 10, type: 1, code: 'x-1'}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-03 20:02:36

您可以尝试以下查询:

代码语言:javascript
复制
db.collection.aggregate([
  {
    $match: { type: 1 }
  },
  {
    $group: {
      _id: null,
      doc: {
        $max: {
          discount_value: "$discount_value",
          type: "$type",
          code: "$code"
        }
      }
    }
  }
])

我相信它将获得字段$max上的discount_value,并从doc discount_value is max中获得相应的type & code值。

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

代码语言:javascript
复制
db.collection.aggregate([
  {
    $match: { type: 1 }
  },
  {
    $sort: { discount_value: -1 } // sort in desc order
  },
  {
    $limit: 1
  }
])

测试: 蒙古操场

注:

在DB上而不是在操场上测试第一个查询。在第一个查询中,如果希望将$replaceRoot字段作为文档的根,则可以使用doc作为最后阶段。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62181108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档