Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query array of nested documents for highest value of field

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 }
    ]
}
like image 975
August Avatar asked Mar 22 '23 21:03

August


1 Answers

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.

like image 192
Shad Avatar answered Mar 31 '23 12:03

Shad