Mongo:如何计算字段中有多少值?

时间:2013-05-20 16:44:05

标签: mongodb

我有收藏品

[
    {
        data: {
            height: 1,
            width:  2
        }
    },{
        data: {
            height: 3,
            width:  2
        }
    },{
        data: {
            height: 3,
            width:  1
        }
    }
]

如何计算data.height中的1和3以及data.width中的1和2?基本上我需要像

这样的结果
{
    data: {
        haight: {
            "1": 1,
            "3": 2
        },
        width:  {
            "1": 1,
            "2": 2
        }
    }
}

由于

2 个答案:

答案 0 :(得分:1)

现在我用mapReduce得到了我需要的东西,它是“范围”参数

db.myCollection.mapReduce(
    function(){
        if( this.data.height in res.data.height === false ) res.data.height[this.data.height] = 0;
        if( this.data.width in res.data.width === false ) res.data.width[this.data.width] = 0;

        res.data.height[this.data.height]++;
        res.data.width[this.data.width]++;

        emit('id', 1);
    },
    function(){
        return res;
    },
    {
        out: {inline: 1},
        scope: {
            res: {
                data:{
                    height: {},
                    width:  {}
                }
            }
        }
    }
)

答案 1 :(得分:0)

  

如何计算data.height中的1和3以及data.width中的1和2?

可以单独聚合每个值(如其他答案所示)。或者,您可以使用单个命令聚合这两个值:

db.test.aggregate({$group: {_id: "$data.height", width: {$push: "$data.width"}, heightCount: {$sum: 1}}},
    {$project: {height: {id: "$_id", count: "$heightCount"}, width: 1}},
    {$unwind: "$width"},
    {$group: {_id: "$width", widthCount: {$sum: 1}, height: {$addToSet: "$height"}}},
    {$unwind: "$height"},
    {$group: {_id: null, width: {$addToSet: {id: "$_id", count: "$widthCount"}}, height: {$addToSet: "$height"}}})
  

我如何计算data.width中数据中的 1和3以及数据中的1和2

如果您只想在data.height中聚合 1和3,在data.width 中聚合1和2,那么您可以将以下命令放在管道的开头:

{$match: {$and: [{$or: [{"data.width": 1}, {"data.width": 2}]}, {$or: [{"data.height": 1}, {"data.height": 3}]}]}}
相关问题