MongoDB嵌入式数组属性的平均值(使用Java和MongoJack)

时间:2016-05-04 18:51:23

标签: java mongodb mongojack database nosql

我有一个名为"餐厅"看起来像这样:

   {
     "_id" : ObjectId("51236fbc3004f02f87c62e8e"),
     "name" : "Some very fancy name"
      reviews: [
        {"id" : 1,
         "text" : "saffas"
         "rating" : 3,
        }
        {"id" : 2,
         "text" : "fsafasfas"   
         "rating" : 4,
        }
    ]
}

我想获得该餐厅所有评论的平均评分。我该怎么做(我使用Java)?

1 个答案:

答案 0 :(得分:0)

运行以下聚合管道以获得餐厅的平均评分:

Mongo shell

var pipeline = [
    { "$unwind": "$reviews" },
    {
        "$group": {
            "_id": "$name",
            "avg_rating": { "$avg": "$reviews.rating" }
        }
    }
]

db.Restaurants.aggregate(pipeline);

这可以转换为Java:

Java测试实施

public class JavaAggregation {
    public static void main(String args[]) throws UnknownHostException {

        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("test");

        DBCollection coll = db.getCollection("Restaurants");

        // create the pipeline operations, first with the $unwind
        DBObject unwind = new BasicDBObject("$unwind", "$reviews");

        // build the $group operations
        DBObject groupFields = new BasicDBObject("_id", "$name");
        groupFields.put("avg_rating", new BasicDBObject("$avg", "$reviews.rating"));

        DBObject group = new BasicDBObject("$group", groupFields);
        List<DBObject> pipeline = Arrays.asList(unwind, group);

        AggregationOutput output = coll.aggregate(pipeline);

        for (DBObject result : output.results()) {
            System.out.println(result);
        }
    }
}