0

I have a document in MongoDB:

{
        "_id" : ObjectId("111111111111111111111111"),
        "taskName" : "scan",
        "nMapRun" : {
                ...
                "hosts" : {
                        ...
                        "distance" : {
                                "value" : "1"
                        },..
}

I'm interested in the field: nMapRun.hosts.distance.value How do I get ten maximum values ​​of the field . Could you give an example of a Java?

0

1 Answer 1

1

The aggregation operation in shell:

db.collection.aggregate([
{$sort:{"nMapRun.hosts.distance.value":-1}},
{$limit:10},
{$group:{"_id":null,"values":{$push:"$nMapRun.hosts.distance.value"}}},
{$project:{"_id":0,"values":1}}
])

You need to build the corresponding DBObjects for each stage as below:

    DBObject sort = new BasicDBObject("$sort", 
                    new BasicDBObject("nMapRun.hosts.distance.value", -1));
    DBObject limit = new BasicDBObject("$limit", 10);
    DBObject groupFields = new BasicDBObject( "_id", null);
    groupFields.put("values", 
                    new BasicDBObject( "$push","$nMapRun.hosts.distance.value"));
    DBObject group = new BasicDBObject("$group", groupFields);
    DBObject fields = new BasicDBObject("values", 1);
    fields.put("_id", 0);
    DBObject project = new BasicDBObject("$project", fields );

Running the aggregation pipeline:

    List<DBObject> pipeline = Arrays.asList(sort, limit, group, project);
    AggregationOutput output = coll.aggregate(pipeline);
    output.results().forEach(i -> System.out.println(i));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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