mysql - How to get distinct result in Mongo DB? -
i using mongodb 2.6.5. have books collection.
> db.books.find() { "_id" : "5476f8b5e4b04367d6c95010", "author" : "abc", "title" : "xyz", "isbnno" : "9781887902991", "category" : "computer" } { "_id" : "5476fae0e4b0016adffd08e4", "author" : "bcd", "title" : "uvw", "isbnno" : "9781887902991", "category" : "computer" } { "_id" : "5476fb7ce4b0016adffd08e5", "author" : "cde", "title" : "pqr", "isbnno" : "9781887902991", "category" : "biography" }
i want result :
{ "_id" : "5476fae0e4b0016adffd08e4", "author" : "bcd", "title" : "uvw", "isbnno" : "9781887902991", "category" : "computer" } { "_id" : "5476fb7ce4b0016adffd08e5", "author" : "cde", "title" : "pqr", "isbnno" : "9781887902991", "category" : "biography" }
i mean 1 book each category “group category” in mysql.
how can achieve this?
thanks in advance.
you need use aggregate pipeline $group
, $project
operators.
- group based on category.
- pick values of first record in each group.
- project record each group.
the code:
db.books.aggregate([ {$group:{"_id":"$category", "author":{$first:"$author"}, "title":{$first:"$title"}, "isbnno":{$first:"$isbnno"}, "category":{$first:"$category"}}}, {$project:{"_id":0,"author":1, "title":1,"isbnno":1,"category":1}} ])
Comments
Post a Comment