从聚合中获取文档

时间:2013-11-27 15:08:27

标签: java mongodb

这是对这篇文章的一种扩展:Query array of nested documents for highest value of field

说我有这个文件结构:

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

我将它与以下内容合并:

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

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

{"text" : "this is another nested document", "value" : 2 }

2 个答案:

答案 0 :(得分: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" } 
    } }
]);

您的结果是:

{
    "result" : [
        {
            "_id" : null,
            "text" : "this is another nested document",
            "value" : 2
        }
    ],
    "ok" : 1
}

如果您还需要原始_id,那么您也可以在$group中执行此操作:

{ $group: { 
    _id: null, 
    original_id: { $first: "$_id" },
    text: { $first: "$array.text" }, 
    value: { $max: "$array.value" } 
} }

答案 1 :(得分:0)

我认为以下查询可以解决您的问题。

db.collection.aggregate([
    { $match: { _id: new ObjectId("526d89571cd72ce9dbb6b443") } },
    { $unwind: "$array" },
    { $group: { _id: "$array.text", value: { $max: "$array.value" } } },
    {$limit : 1}
]);

这将打印结果如下:

"result" : [
    {
        "_id" : "this is another nested document",
        "value" : 2
    }
]