如何根据唯一的嵌入数组值进行计数

时间:2016-08-22 13:35:37

标签: mongodb

我的收藏:

{ "_id" : 1, "type" : "A", "types" : [ "type1://asfasd", "type2://xcvxcv" ] }
{ "_id" : 2, "type" : "B", "types" : [ "type1://xcv" ] }
{ "_id" : 3, "type" : "C", "types" : [ "type2://aewqqwe" ] }
{ "_id" : 4, "type" : "D", "types" : [ "type2://xcxc" ] }

我希望最终结果可以计算并告诉我:

type1 -> 2 (because there are total of 2 documents that has type1)
type2 -> 3 (because there are total of 3 documents that has type2)

1 个答案:

答案 0 :(得分:0)

使用map-reduce,您可以根据所需的字符串使用正则表达式提取分组文档,即type1,type2,type69等。

据我所知,你不能使用聚合管道和小组阶段的正则表达式。

因此,在map阶段,遍历types数组,使用正则表达式提取字符串,即type1,type2,而不是将此字符串作为键发出,值为1.
在reduce阶段,具有相同键的所有值都将在一个列表中,而不是只计算列表的长度:

var map = function map(){
    for (type in this.types){
        var str = this.types[type];
        var rx = /type\d+/;
        var match = str.match(rx);
        emit (match[0], 1);
    }
};

var reduce = function(key, values){
    return values.length
};


db.runCommand({"mapReduce":"collection", map:map, reduce:reduce, out:{replace:"collection2"}})

您数据的Ex输出:

{ "_id" : "type1", "value" : 2 }
{ "_id" : "type2", "value" : 3 }