展开和匹配后的组数组 [英] 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);
但我想要一个 Team 对象,它以数组的形式包含所有玩家.我怎样才能做到这一点?
But I would like to have one Team object, that contains all players as an array. How can I achieve that?
推荐答案
在 _id
上使用 Group
和 $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);
如果您希望在最终文档中包含任何其他字段,请在组操作期间将其添加到 _id
字段中.
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'}})
这篇关于展开和匹配后的组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文