簡體   English   中英

查詢嵌套文檔的數組以獲得最高的字段值

[英]Query array of nested documents for highest value of field

我正在嘗試查詢mongodb中的嵌套文檔數組,並獲取該嵌套文檔中特定字段的最高值。 (在java中)

這是文檔結構的一個示例,我想在其中找到數組中"value"字段的"value"

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

您還可以嘗試現代方法 - 聚合框架

1)為集合中的所有元素找到最大數組'value':

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驅動程序和聚合框架

你可以使用MongoDB 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開發環境,但這里有一篇關於如何用Java進行Map / Reduce查詢的文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM