嵌套文档的查询数组字段的最高值 [英] Query array of nested documents for highest value of field

查看:100
本文介绍了嵌套文档的查询数组字段的最高值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查询MongoDB中嵌套文档的数组,并同时获得该文件嵌套在某一特定领域的最高值。 (在Java中)

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

  {
    _id:的ObjectId(526d89571cd72ce9dbb6b443),
    阵:
         {文:这是一个嵌套的文档,价值:1},
         {文:这是又一个嵌套的文档,价值:2}
    ]
}


解决方案

您也可以尝试现代的方式 - 聚合框架

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

  db.collection.aggregate([
    {$放松:$阵},
    {$组:{_id:$ _id,值:{$最大:$ array.value}}}
]);

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

  db.collection.aggregate([
    {$匹配:{_id:新的ObjectId(526d89571cd72ce9dbb6b443)}},
    {$放松:$阵},
    {$组:{_id:NULL,值:{$最大:$ array.value}}}
]);

使用真实采集名称而不是在这些例子中。

如何在Java中的MongoDB驱动程序使用聚合的一些信息:的 Java驱动程序和聚合框架

I'm trying to query an array of nested documents in mongodb, and also get the highest value of a particular field in that nested document. (In java)

Here is an example of the document structure, where I want to find the largest value of the "value" field in the array.

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

解决方案

You can also try modern approach - aggregation framework:

1) Find maximum array 'value' for all elements in collection:

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

2) Find maximum array 'value' for specified element:

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

Use real collection name instead of collection in these examples.

Some information on how to use aggregation in Java MongoDB driver: Java Driver and Aggregation Framework.

这篇关于嵌套文档的查询数组字段的最高值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆