从聚合中获取文档

Aug*_*ust 0 java mongodb

这是对这篇文章的一种扩展:查询最高字段值的嵌套文档数组

说我有这个文档结构:

{
    "_id" : ObjectId("526d89571cd72ce9dbb6b443"),
    "array" : [ 
         {"text" : "this is a nested document", "value" : 1 },
         {"text" : "this is another nested document", "value" : 2 }
    ]
}
Run Code Online (Sandbox Code Playgroud)

而且我将它与以下内容合并:

db.collection.aggregate([
    { $match: { _id: new ObjectId("526d89571cd72ce9dbb6b443") } },
    { $unwind: "$array" },
    { $group: { _id: null, value: { $max: "$array.value" } } }
]);
Run Code Online (Sandbox Code Playgroud)

如何在"array"包含聚合结果的数组中获取文档- "value" : 2.我希望能够得到这个:

{"text" : "this is another nested document", "value" : 2 }
Run Code Online (Sandbox Code Playgroud)

Der*_*ick 5

你需要做一个$unwind然后做一个$sort.如果你这样做,你可以使用$first:

db.collection.aggregate([
    { $match: { _id: new ObjectId("526d89571cd72ce9dbb6b443") } },
    { $unwind: "$array" },
    { $sort: { "array.value": -1 } },
    { $group: { 
        _id: null, 
        text: { $first: "$array.text" }, 
        value: { $max: "$array.value" } 
    } }
]);
Run Code Online (Sandbox Code Playgroud)

那么你的结果是:

{
    "result" : [
        {
            "_id" : null,
            "text" : "this is another nested document",
            "value" : 2
        }
    ],
    "ok" : 1
}
Run Code Online (Sandbox Code Playgroud)

如果您还需要原件_id,那么您也可以在以下位置执行此操作$group:

{ $group: { 
    _id: null, 
    original_id: { $first: "$_id" },
    text: { $first: "$array.text" }, 
    value: { $max: "$array.value" } 
} }
Run Code Online (Sandbox Code Playgroud)