如何从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'}
}
}这个查询将从discount_value (10)键和键_id检索最大值,但是如果我没有操作来执行这些键,那么如何检索代码并键入键呢?
目前的结果是:
{_id: null, discount_value: 10}预期结果:
{_id: null, discount_value: 10, type: 1, code: 'x-1'}发布于 2020-06-03 20:02:36
您可以尝试以下查询:
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:
db.collection.aggregate([
{
$match: { type: 1 }
},
{
$sort: { discount_value: -1 } // sort in desc order
},
{
$limit: 1
}
])测试: 蒙古操场
注:
在DB上而不是在操场上测试第一个查询。在第一个查询中,如果希望将$replaceRoot字段作为文档的根,则可以使用doc作为最后阶段。
https://stackoverflow.com/questions/62181108
复制相似问题