4

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 }
    ]
}

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Those both return { "result" : [ ], "ok" : 1 }?
@August, since you didn't specify real collection name in your question, I simply named it collection. But you must use real collection name. (I've added this to answer)
3

You can do this pretty easily with a MongoDB map/reduce. Here's the map/reduce I'd write:

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;
};

and, while I don't have a java dev environment ready to go, here's an article on how to do Map/Reduce queries in Java.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.