【问题标题】:Query array of nested documents for highest value of field查询嵌套文档数组以获取字段的最高值
【发布时间】:2026-01-28 19:00:02
【问题描述】:

我正在尝试在 mongodb 中查询嵌套文档数组,并获取该嵌套文档中特定字段的最大值。 (在java中)

这里是一个文档结构的例子,我想在其中找到数组中"value"字段的最大值。

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

【问题讨论】:

    标签: java arrays mongodb


    【解决方案1】:

    您也可以尝试现代方法 - aggregation framework:

    1) 查找集合中所有元素的最大数组“值”:

    db.collection.aggregate([
        { $unwind: "$array" },
        { $group: { _id: "$_id", value: { $max: "$array.value" } } }
    ]);
    

    2) 查找指定元素的最大数组“值”:

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

    在这些示例中使用真实的集合名称而不是 collection

    有关如何在 Java MongoDB 驱动程序中使用聚合的一些信息:Java Driver and Aggregation Framework

    【讨论】:

    • 两者都返回{ "result" : [ ], "ok" : 1 }?
    • @August,由于您没有在问题中指定真实的集合名称,我只是将其命名为collection。但是你必须使用真实的集合名称。 (我已经添加了这个来回答)
    【解决方案2】:

    您可以使用 MongoDB map/reduce 轻松完成此操作。这是我要写的 map/reduce:

    map = function() { 
      for (var a in this.array) { 
        emit('value', a.value); 
      }
    };
    
    reduce_max = function(key, values) {
        var max = values[0];
        values.forEach(function(val) {
            if (val > max) max = val;
        })
        return max;
    };
    

    虽然我还没有准备好 Java 开发环境,但 here's an article 了解如何在 Java 中进行 Map/Reduce 查询。

    【讨论】: