在Mongo中使用聚合的嵌套查询

时间:2014-11-29 10:12:24

标签: mongodb database

我在MongoDB中有一个文档:

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

我对该领域感兴趣: nMapRun.hosts.distance.value 如何获得该字段的十个最大值。 你能举一个Java的例子吗?

1 个答案:

答案 0 :(得分:1)

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

您需要为每个阶段构建相应的DBObjects,如下所示:

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

运行aggregation管道:

    List<DBObject> pipeline = Arrays.asList(sort, limit, group, project);
    AggregationOutput output = coll.aggregate(pipeline);
    output.results().forEach(i -> System.out.println(i));