没有获得 $group 聚合的投影字段

Not getting projected fields with $group aggregation

我的聚合查询是:

db.POLICY.aggregate([
    {$group:{_id:"$_id",max:{$max:"$priority"}}},
    {$project:{name:1, AppList:1, status:1}},{$limit:1}
]);

它给了我一个只有 _id 字段的文档。 我错过了什么吗?

$group 的输出不包含输入中的任何字段,除非您指定它们。换句话说,$group 的输出将不包含 nameAppListstatus。但是,在这种情况下,它将包含一个 _idmax 字段。阅读有关 $group 字段 here.

的更多信息

根据您对上述现有答案的评论,您似乎想要获得具有最大优先级值的文档。解决此问题的一种方法涉及使用 $first operator which returns a value from the first document for each group. Order is only defined if the documents are in a defined order hence you'd need the $sort pipeline step before implementing this in the $group 对输入文档进行排序。以下示例演示了这种方法:

db.POLICY.aggregate([
    { "$sort": { "priority": -1 } },
    {
        "$group": {
            "_id": null,
            "name": { "$first": "$name" }, 
            "AppList": { "$first": "$AppList" }, 
            "status": { "$first": "$status" }           
        }
    }
])

上述操作指定一个_id值为null来计算所有输入文档作为一个整体的累加值,然后$first累加器计算第一个name,[=当按 priority 字段降序排序时,每个文档的 17=] 和 status 字段,从而为您提供最大 priority.

的文档