An array of requests for attached documents for the maximum field value

I am trying to query an array of nested documents in mongodb, and also get the maximum value of a specific field in this nested document. (In java)

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

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

You can also try the modern approach - aggregation structure :

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

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

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

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

collection.

, Java MongoDB-: Java Driver and Aggregation Framework.

+4

MongoDB/. / :

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-dev, , , Map/Reduce Java.

+3

All Articles