展开和匹配后的组数组

时间:2015-05-08 08:48:16

标签: mongodb mongoose aggregation-framework

我有两次嵌套架构:

mongoose.model('Team', mongoose.Schema(
{
 players : [{ 
    trikots : [{
        isNew : Boolean,
        color : String
    }]
 }]
})

目前,我的查询如下所示:

Team.aggregate()
        .match({'_id' : new ObjectId(teamId)})
        .unwind('players')
        .unwind('players.trikots')
        .match({'players.trikots.isNew' : 'red', 'players.trikots.isNew' : true})
        .exec(sendBack);

但是我希望有一个Team对象,它包含所有玩家作为数组。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:15)

使用Group _id$push运算符将所有玩家归为阵列。

Team.aggregate()
        .match({'_id' : new ObjectId(teamId)})
        .unwind('players')
        .unwind('players.trikots')
        .match({'players.trikots.color' : 'red', 'players.trikots.isNew' : true})
        .group({'_id':'$_id','players': {'$push': '$players'}})
        .exec(sendBack);

如果您希望在最终结果中包含任何其他字段,请在组操作期间将其添加到_id字段。

.group({'_id':{'_id':'$_id','some_other_field':'$some_other_field'},'players': {'$push': '$players'}})