简体   繁体   English

MongoDB聚合将两个不同的字段合并为一个并获取计数

[英]MongoDB aggregate merge two different fields as one and get count

I have following data in MongoDB: 我在MongoDB中有以下数据:

[{id:3132, home:'NSH', away:'BOS'}, {id:3112, home:'ANA', away:'CGY'}, {id:3232, home:'MIN', away:'NSH'}]

Is it possible to get total game count for each team with aggregate pipeline? 是否可以通过汇总渠道获得每个团队的总比赛数?

desired result: 预期结果:

[{team: 'NSH', totalGames: 2}, {team:'MIN', totalGames: 1}, ...}]

i can get each on seperately to their own arrays with two aggregate calls: 我可以通过两个聚合调用将每个单独地分配到它们自己的数组:

[{$group: {_id: "$home", gamesLeft: {$sum: 1}}}]

and

[{$group: {_id: "$away", gamesLeft: {$sum: 1}}}]

resulting 结果

var homeGames = [ { _id: 'NSH', totalGames: 1 }, { _id: 'SJS', totalGames: 2 }, ...]
var awayGames = [ { _id: 'NSH', totalGames: 1 }, { _id: 'SJS', totalGames: 4 }, ...]

But i really want to get it working with just one query. 但是我真的很想让它只处理一个查询。 If not possible what would be the best way to combine these two results in to one using javascript? 如果不可能的话,使用JavaScript将这两个结果合并为一个的最佳方法是什么?

After some puzzling, I found a way to get it done using an aggregate pipeline. 经过一番困惑之后,我找到了一种使用聚合管道来完成此工作的方法。 Here is the result: 结果如下:

db.games.aggregate([{
        $project: {
            isHome: { $literal: [true, false] },
            home: true,
            away: true
        }
    }, {
        $unwind: '$isHome'
    }, {
        $group: {
            _id: { $cond: { if: '$isHome', then: '$home', else: '$away' } },
            totalGames: { $sum: 1 }
        }
    }
]);

As you can see it consists of three stages. 如您所见,它包括三个阶段。 The first two are meant to duplicate each document into one for the home team and one for the away team. 前两个用于将每个文档复制到一个用于主队的文件和一个用于客队的文件。 To do this, the project stage first creates a new isHome field on each document containing a true and a false value, which the unwind stage then splits into separate documents containing either the true or the false value. 为此,项目阶段首先在每个包含true和false值的文档上创建一个新的isHome字段,然后展开阶段将其拆分成包含true或false值的单独文档。

Then in the group phase, we let the isHome field decide whether to group on the home or the away field. 然后在分组阶段,让isHome字段决定是在home字段还是away字段上分组。

It would be nicer if we could create a team field in the project step, containing the array [$home, $away] , but mongo only supports adding array literals here, hence the workaround. 如果我们可以在项目步骤中创建一个包含数组[$home, $away]team字段,那就更好[$home, $away] ,但是mongo仅支持在此处添加数组文字,因此可以解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM