2014-12-02 45 views
1

我正在使用mongoDB 2.6.5。我有一本藏书。如何在MongoDB中获得不同的结果?

> 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

您需要使用$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}} 
])