How to get a rating average in MongoDB based on duplicate ids?

MongoDBDatabaseBig Data Analytics

For average in MongoDB, use the $avg. Let us create a collection with documents. Here, we have duplicate ids with rating for each −

> db.demo606.insertOne({id:1,rating:5});{
   "acknowledged" : true, "insertedId" : ObjectId("5e972dfbf57d0dc0b182d623")
}
> db.demo606.insertOne({id:1,rating:4});{
   "acknowledged" : true, "insertedId" : ObjectId("5e972dfef57d0dc0b182d624")
}
> db.demo606.insertOne({id:2,rating:3});{
   "acknowledged" : true, "insertedId" : ObjectId("5e972e09f57d0dc0b182d625")
}
> db.demo606.insertOne({id:1,rating:null});{
   "acknowledged" : true, "insertedId" : ObjectId("5e972e0ef57d0dc0b182d626")
}
> db.demo606.insertOne({id:2,rating:null});{
   "acknowledged" : true, "insertedId" : ObjectId("5e972e15f57d0dc0b182d627")
}
> db.demo606.insertOne({id:2,rating:3});{
   "acknowledged" : true, "insertedId" : ObjectId("5e972e1bf57d0dc0b182d628")
}

Display all documents from a collection with the help of find() method −

> db.demo606.find();

This will produce the following output −

{ "_id" : ObjectId("5e972dfbf57d0dc0b182d623"), "id" : 1, "rating" : 5 }
{ "_id" : ObjectId("5e972dfef57d0dc0b182d624"), "id" : 1, "rating" : 4 }
{ "_id" : ObjectId("5e972e09f57d0dc0b182d625"), "id" : 2, "rating" : 3 }
{ "_id" : ObjectId("5e972e0ef57d0dc0b182d626"), "id" : 1, "rating" : null }
{ "_id" : ObjectId("5e972e15f57d0dc0b182d627"), "id" : 2, "rating" : null }
{ "_id" : ObjectId("5e972e1bf57d0dc0b182d628"), "id" : 2, "rating" : 3 }

Following is the query to get rating average based on duplicate ids −

> db.demo606.aggregate(
...    [
...       { "$group": {
...          "_id": "$id",
...          "AverageRating": { "$avg": { "$ifNull": ["$rating",0 ] } }
...       }}
...    ]
... );

This will produce the following output −

{ "_id" : 2, "AverageRating" : 2 }
{ "_id" : 1, "AverageRating" : 3 }
raja
Published on 15-May-2020 11:21:47
Advertisements