2014-12-02 44 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}} 
])