Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group array after unwind and match

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?

like image 220
Florian Mozart Avatar asked May 08 '15 08:05

Florian Mozart


People also ask

What is unwind in aggregation?

Example: $unwind The following aggregation $unwind stage is used to output a document for each element in the sizes array. Here from the result it shows that, each document is identical to the input document except for the value of the sizes field that contain the value from the original sizes array.

How do you unwind more than one array?

To unwind, use $unwind. The $unwind deconstructs an array field from the input documents to output a document for each element.

What does $unwind do?

$unwind treats the sizes field as a single element array if: the field is present, the value is not null, and. the value is not an empty array.

How do I use $Push in MongoDB?

If the field is absent in the document to update, $push adds the array field with the value as its element. If the field is not an array, the operation will fail. If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push .


1 Answers

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'}})
like image 90
thegreenogre Avatar answered Jan 04 '23 20:01

thegreenogre