简体   繁体   中英

MongoDB average value of attribute of embedded array (using Java and MongoJack)

I have a collection named "Restaurants" which looks like this:

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

I would like to get an average rating of all of the reviews of the restaurant. How can I do this (I use Java)?

Run the following aggregation pipeline to get the average rating of a restaurant:


Mongo shell

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

db.Restaurants.aggregate(pipeline);

This can be translated to Java as:


Java test implementation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM