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?
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.
To unwind, use $unwind. The $unwind deconstructs an array field from the input documents to output a document for each element.
$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.
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 .
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'}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With