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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With