展开和匹配后分组数组
Group array after unwind and match
我有一个两次嵌套的模式:
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 对象,它包含所有球员作为一个数组。我怎样才能做到这一点?
在 _id
上使用 Group
和 $push
运算符将 return 所有玩家放入数组中。
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'}})
我有一个两次嵌套的模式:
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 对象,它包含所有球员作为一个数组。我怎样才能做到这一点?
在 _id
上使用 Group
和 $push
运算符将 return 所有玩家放入数组中。
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'}})