展开并匹配后对数组进行分组 [英] Group array after unwind and match

查看:71
本文介绍了展开并匹配后对数组进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两次嵌套的架构:

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对象,该对象包含所有玩家作为数组.我该如何实现?

But I would like to have one Team object, that contains all players as an array. How can I achieve that?

推荐答案

_id上将Group

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆