2014-12-05 91 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