我使用的是mongoDB 2.6.5。我有一本书籍收藏。
> 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" }
我想要结果为:
{ "_id" : "5476fae0e4b0016adffd08e4", "author" : "bcd", "title" : "uvw", "isbnNo" : "9781887902991", "category" : "Computer" }
{ "_id" : "5476fb7ce4b0016adffd08e5", "author" : "cde", "title" : "pqr", "isbnNo" : "9781887902991", "category" : "Biography" }
我的意思是来自每个类别的任何一本书,例如mySQL中的“按类别分组”。
我怎样才能做到这一点?
提前致谢。
答案 0 :(得分:0)
您需要将汇总管道与$group
和$project
运算符一起使用。
守则:
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}}
])