对 Map Function 进行故障排除

    map function 是一个 JavaScript function,它将 value 与 key 关联或“maps”,并在map-reduce操作期间发出 key 和 value 对。

    要验证map function 发出的keyvalue对,请编写自己的emit function。

    考虑一个包含以下原型文档的集合orders

    1. {
    2. _id: ObjectId("50a8240b927d5d8b5891743c"),
    3. cust_id: "abc123",
    4. ord_date: new Date("Oct 04, 2012"),
    5. status: 'A',
    6. price: 250,
    7. items: [ { sku: "mmm", qty: 5, price: 2.5 },
    8. { sku: "nnn", qty: 5, price: 2.5 } ]
    9. }
    • 为每个文档定义_ma 功能

      1. var map = function() {
      2. emit(this.cust_id, this.price);
      3. };
    • 定义emit function 以打印 key 和 value:

      1. var emit = function(key, value) {
      2. print("emit");
      3. print("key: " + key + " value: " + tojson(value));
      4. }
    • 使用orders集合中的单个文档调用map function:

      1. var myDoc = db.orders.findOne( { _id: ObjectId("50a8240b927d5d8b5891743c") } );
      2. map.apply(myDoc);
    • 验证 key 和 value 对是否符合预期。

      1. emit
      2. key: abc123 value:250
    • 使用orders集合中的多个文档调用map function:

      1. var myCursor = db.orders.find( { cust_id: "abc123" } );
      2. while (myCursor.hasNext()) {
      3. var doc = myCursor.next();
      4. print ("document _id= " + tojson(doc._id));
      5. map.apply(doc);
      6. print();
      7. }
    • 验证 key 和 value 对是否符合预期。

    也可以看看

    mapfunction 必须满足各种要求。有关map` function 的所有要求的列表,请参阅MapReducemongo shell 辅助方法db.collection.mapReduce()

    译者:李冠飞

    校对:

    参见

    原文 - Troubleshoot the Map Function