Search code examples
arraysmongodbnosqlmongodb-querynosql-aggregation

MongoDB Highest rated books, to display title


db.Books.aggregate( 
    {$unwind:'$rating'}, //unwinds rating array
    {$group:{_id:"$ISBN",avgR:{$avg:'$rating.book_rating'}}},
    {$sort : { avgR: -1 } }
).limit(5);

This query returns top 5 highest rated books

Collection is like:

{
    ISBN,
    Title,
    Rating:[ 
    {
        user,
        book_rating
    }
    ]
}

I have this query, within this i want to output Title of book. How do I project it out? {$project: {_id:0,"title":""}} // Wrong apparently


Solution

  • Quoted by @stackoverflow.com/users/1913537/ori-dar

    Then group by both: {$group:{_id: {isbn: "$ISBN", title: "$Title"}.