2014-12-05 108 views
0

我麻煩過濾並在mongodb上分組。我真的沒有承認它是如何工作的。貓鼬分組錯誤

例如,在此查詢:

Room.aggregate(
[{ 
    "$where": { "roomId" : myIdHere }, 
    "$group": { 
     "_id": '$mobileUser.genderType', 
     "genderTypeCount": { 
      "$sum": 1 
     } 
    } 
}] 

房型號:

var roomModelSchema = mongoose.Schema({ 
    roomId: String, 
    mobileUser: { 
     facebookId: String, 
     email: String, 
     name: String, 
     photoUrl: String, 
     genderType: String, 
     birthday: Date, 
     city: String  
    }, 
    insertDate: Date 
}) 

我應該怎麼做由roomId和group by genderType過濾?

回答

1

使用$match代替$where,並把每個管道運行到它自己的對象:

Room.aggregate([ 
    { "$match": { "roomId" : myIdHere } }, 
    { "$group": { 
     "_id": '$mobileUser.genderType', 
     "genderTypeCount": { 
      "$sum": 1 
     } 
    }} 
], function(err, result) {...}) 
+0

完美!謝啦。我有一個問題,當你說'管道'我怎麼能比較這個詞與關係數據庫?試圖低估它我瘋了。 – Ren4n 2014-12-05 21:14:23

+1

您可以閱讀關於聚合管道[此處](http://docs.mongodb.org/manual/core/aggregation-introduction/#aggregation-pipelines)。 – JohnnyHK 2014-12-05 21:15:52