Skip to content

Instantly share code, notes, and snippets.

@ktkaushik
Last active September 25, 2016 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ktkaushik/f2a5bf34ef847f5c9af7f2598e76482d to your computer and use it in GitHub Desktop.
Save ktkaushik/f2a5bf34ef847f5c9af7f2598e76482d to your computer and use it in GitHub Desktop.
aggregate ratings mongodb
// {
// "result": [
// {
// "_id": 5,
// "count": 2
// },
// {
// "_id": 4,
// "count": 1
// }
// ],
// "ok": 1
// }
db.ratings.aggregate([
{$match: {book: ObjectId("57e111142a52fe257e5d1d42")}},
{$group: {_id: "$value", count: {$sum: 1}}}
])
// {
// "result": [
// {
// "_id": 1,
// "ratings": 1
// },
// {
// "_id": 2,
// "ratings": 2
// },
// {
// "_id": 3,
// "ratings": 2
// },
// {
// "_id": 5,
// "ratings": 11
// },
// {
// "_id": 4,
// "ratings": 4
// },
// {
// "_id": 0,
// "ratings": 31
// }
// ],
// "ok": 1
// }
db.ratings.aggregate([
{ $group: {
_id: '$value',
ratings: { $sum: 1 }
}}
])
// {
// "result": [
// {
// "_id": ObjectId("57e6bef7cad79fa38555c643"),
// "total": 2
// },
// {
// "_id": ObjectId("57e111142a52fe257e5d1d42"),
// "total": 2
// }
// ],
// "ok": 1
// }
db.ratings.aggregate([
{$match: {book: {$in: [ObjectId("57e111142a52fe257e5d1d42"), ObjectId('57e6bef7cad79fa38555c643')]}}},
{$group: {_id: {book: "$book", value: "$value"} } },
{$group: {_id: "$_id.book", total: {$sum: 1}}},
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment