我有两次嵌套架构:
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对象,它包含所有玩家作为数组。我怎样才能做到这一点?
答案 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'}})