为什么MapReduce返回_id和值参数?

时间:2014-10-14 22:24:51

标签: mongodb mapreduce

我需要创建一个map reduce函数,它将搜索文档中的某些条件,然后如果满足它们,则返回整个文档(或创建一个包含匹配文档的新表)。以下是我需要做的简化示例,但请记住,实际文档中有更多内容。

假设我有两份文件:

文件#1:

{
  "_id": ObjectId("542ec1a91d40cafd58b928b4"),
  "billing": {
    "category1": {
      "0": {
        "mode": "email",
        "email": {
          "0": "test@what.com" 
        } 
      } 
    },
    "category2": {
      "0": {
        "mode": "email",
        "email": {
          "0": "who@cares.net" 
        } 
      } 
    }
  }
}

文件#2:

{
  "_id": ObjectId("542ec1a91d40cafd58b928b4"),
  "billing": {
    "category1": {
      "0": {
        "mode": "email",
        "email": {
          "0": "test@what.com" 
        } 
      } 
    },
    "category2": {
      "0": {
        "mode": "email"
      } 
    }
  }
}

我需要确定哪些文档的模式值为"电子邮件"但没有相应的电子邮件元素。这是我到目前为止所得到的:

var mapFunction = function() {
  for(var bKey in this.billing) {
    for (var bSubKey in this.billing[bKey]) {

      var modeIsEmail = (this.billing[bKey][bSubKey].mode == 'email');
      var emailElementIsMissing = (typeof this.billing[bKey][bSubKey].email == 'undefined');

      if (modeIsEmail && emailElementIsMissing) {
        var newDoc = this;
        delete newDoc._id;
        emit('document', newDoc);
      }
    }
  }
}

var reduceFunction = function(documentKey, badRecord) {
  return badRecord;
}


db.cust.mapReduce(mapFunction, reduceFunction, { out:"test_reduce"})

虽然这在技术上有效,但我对输出的结构感到恼火和困惑。这就是输出的样子:

"_id" : "document",
"value" : {
  "billing": {
    "category1": {
      "0": {
        "mode": "email",
        "email": {
          "0": "test@what.com" 
        } 
      } 
    },
    "category2": {
      "0": {
        "mode": "email",
        "email": {
          "0": "who@cares.net" 
        } 
      } 
    }
  }
}

为什么我的结果结构与原始文档不完全相同?我需要的是摆脱" _id"和"价值"根部的元素并返回:

{
  "_id": ObjectId("542ec1a91d40cafd58b928b4"),
  "billing": {
    "category1": {
      "0": {
        "mode": "email",
        "email": {
          "0": "test@what.com" 
        } 
      } 
    },
    "category2": {
      "0": {
        "mode": "email"
      } 
    }
  }
}

如何做到这一点?

0 个答案:

没有答案