展开和匹配后的组数组

Flo*_*art 5 mongoose mongodb aggregation-framework

我有两次嵌套架构:

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

现在,我的查询如下所示:

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

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

the*_*gre 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);
Run Code Online (Sandbox Code Playgroud)

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

.group({'_id':{'_id':'$_id','some_other_field':'$some_other_field'},'players': {'$push': '$players'}})
Run Code Online (Sandbox Code Playgroud)