[英]MongoDB average value of attribute of embedded array (using Java and MongoJack)
我有一個名為“Restaurants”的集合,如下所示:
{
"_id" : ObjectId("51236fbc3004f02f87c62e8e"),
"name" : "Some very fancy name"
reviews: [
{"id" : 1,
"text" : "saffas"
"rating" : 3,
}
{"id" : 2,
"text" : "fsafasfas"
"rating" : 4,
}
]
}
我想得到該餐廳所有評論的平均評分。 我該怎么做(我使用Java)?
運行以下聚合管道以獲取餐廳的平均評級:
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.