从两个数组MongoDB的聚集数项 [英] mongodb aggregation count items from two arrays

查看:97
本文介绍了从两个数组MongoDB的聚集数项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在同一个模型中计算两个数组中的项目:

I'm trying to count the items from two arrays within the same model:

型号:

{_id:1
 name:"fun",
   objectsTypeA: [
        objectId_1
        objectId_2
   ],
   objectsTypeB: [
        objectId_5
        objectId_9
   ]
},
{_id:2
 name:"boring",
   objectsTypeA: [
        objectId_3
        objectId_4
   ],
   objectsTypeB: []
}

我试图得到以下结果:

I'm trying to get the following result:

[
  { name:"fun",
    id: 1,
    count:4
  },
  { name:"boring",
    id: 2,
    count: 2
  ] 

我走到这一步,是这样的:

What I got so far is this:

Object.aggregate([
       {$project: {_id:1, name:1, objectsTypeA:1}},
       {$unwind:'$objectsTypeA'},
       {$group: {
           _id: "$name",
    taggableId: {$addToSet:'$_id'},
         count: { $sum: 1}
       }},
   ], function(err, t){
      if (!err){
          res.jsonp(t);
      }
   });

这pretty多少是我想要的,但它仅适用于从我的模型两个阵列之一,我在寻找如何达到这一结果,如果它实际上可能一些建议。

This pretty much is what I want, but it only works for one of the two arrays from my model, I'm looking for some advice on how to reach that result, if it's actually possible.

先谢谢了。

推荐答案

是的,有肯定是这里疑难杂症,那就是如果你试图放松一个空数组结果将失去它的父记录,因为它认为有什么也没有放松。

Yes there certainly is a aggregate gotcha in here and that is if you attempt to unwind an empty array the results will be lost for it's parent record as it considers there is nothing there to unwind.

所以,现在要解决这个最简单的方法是 <强> MA preduce

So right now the easiest way to solve this is with mapReduce:

db.objects.mapReduce(
    function () {
        emit(
            this._id,
            {
                "name": this.name,
                "count": this.objectsTypeA.length + this.objectsTypeB.length
            }
        );
     },
     function(){},
     { "out": { "inline": 1 } }
 )

在MongoDB中的未来版本中有一个 $大小 可供聚集管道运营商,所以你可以简单地做大同小异与骨料:

In future versions of MongoDB there is a $size operator available to the aggregation pipeline, so you can simply do much the same with aggregate:

db.objects.aggregate([
    { "$project": {
        "name": 1,
        "count": { "$add": [ 
            { "$size": "$objectsTypeA" },
            { "$size": "$objectsTypeB" }
        ]}
    }}
])

这篇关于从两个数组MongoDB的聚集数项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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