Group array after unwind and match

2019-01-26 14:10发布

问题:

I have a twice nested schema:

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

For now, my query looks like this:

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

But I would like to have one Team object, that contains all players as an array. How can I achieve that?

回答1:

Use Group on _id with $push operator to return all players into an array.

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);

If you want any other field to be included in the final doucment add it to _id field during group operation.

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