0

我有一個這樣的模型:貓鼬骨料獲得成員總數在一組模型

var field = { 
    createdAt: {type: Date, default: Date.now()}, 
    updatedAt: {type: Date, default: Date.now()}, 
    pic : {type: String, default: 'http://lorempixel.com/400/400/abstract/', writable: true}, 
    thumb : {type: String, default: 'http://lorempixel.com/100/100/abstract/', writable: true}, 

    name: {type: String}, 
    description: {type: String}, 
    isPublic: {type: Boolean, default: true}, 
    members: [{type: Schema.Types.ObjectId, ref: 'Member'}], 
} 

im使用低於此代碼即可獲得Member的ID的成員中字段的總數。

Group.aggregate([ 
    {$match: {_id:req.params.group_id}}, 
    {$group: { 
     _id: '$members', 
     count: {$sum: 1} 
    }} 
], function (err, count) { 
    res.send(count); 
}); 

但它返回併爲空數組[]如何獲得正確的計數?

謝謝。

+1

貓鼬不「自動施放」爲'ObjectId'聚集管道。你需要自己施放它,否則你的'$ match'什麼都不匹配。之前被問過,讓我搜索重複(s)。 –

+1

可能重複的[無法使用貓匹配貓鼬和聚合框架](http://stackoverflow.com/questions/14551387/cant-use-match-with-mongoose-and-the-aggregation-framework) –

+1

同樣在[問題#1399](https://github.com/Automattic/mongoose/issues/1399) –

回答

0

Mongoose在彙總管道中不會「自動加入」到OjectId或任何其他模式類型。所以你的操作沒有任何迴應,

此外,這不會是數組成員的計數方法。

最好使用$size選項,而不是每個文檔數陣成員:

Group.aggregate([ 
    { "$match": { _id: ObjectId(req.params.group_id) }}, 
    { "$group": { 
     "_id": null, 
     "count": { "$sum": { "$size": "$members" } } 
    }} 
], function (err, count) { 
    res.send(count); 
}); 

而且$group_id爲適當捲起,或null這裏用於集合中的所有項目。

如果你想在「每個不同成員的數量」,那麼你將與整個文件(S)$unwind不是進程:

Group.aggregate([ 
    { "$match": { _id: ObjectId(req.params.group_id) }}, 
    { "$unwind": "$members" }, 
    { "$group": { 
     "_id": "$members", 
     "count": { "$sum": 1 } 
    }} 
], function (err, count) { 
    res.send(count); 
}); 
+0

{「$ group」:{ 「_id」:null, 「計數」:{ 「$總和」:{ 「$大小」: 「$成員」}} }} 回報 {名稱: 'MongoError', 消息: '異常:無效的運營商\' $大小\ '', errmsg:'exception:invalid operator''size'', code:15999, ok:0} – CENT1PEDE

+0

@TheGreenFoxx你有哪個MongoDB服務器版本?從MongoDB 2.6開始支持'$ size',所以它一定是舊的。使用'$ unwind'和'null'或'$ _id'處理變量,即使在'$ group'' _id'鍵中也是如此。 –

+0

Oooh我正在使用2.4.9我應該升級。 – CENT1PEDE