[英]How to get nested documents by field value from other documents (ElasticSearch)?
[英]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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.