我正在使用 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 中的“按类别分组”。
我怎样才能做到这一点?
提前致谢。
最佳答案
您需要将聚合管道与 $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}}
])
关于mysql - 如何在 Mongodb 中获得不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27242503/