Troubleshoot the Map Function

The map function is a JavaScript function that associates or “maps”a value with a key and emits the key and value pair during amap-reduce operation.

Note

Starting in version 4.2.1, MongoDB deprecates the use of JavaScriptwith scope (i.e. BSON type 15) forthe map, reduce, and finalize functions. To scopevariables, use the scope parameter instead.

To verify the key and value pairs emitted by the mapfunction, write your own emit function.

Consider a collection orders that contains documents of thefollowing prototype:

  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. }
  • Define the map function that maps the price to thecust_id for each document and emits the cust_id and pricepair:
  1. var map = function() {
  2. emit(this.cust_id, this.price);
  3. };
  • Define the emit function to print the key and value:
  1. var emit = function(key, value) {
  2. print("emit");
  3. print("key: " + key + " value: " + tojson(value));
  4. }
  • Invoke the map function with a single document from the orderscollection:
  1. var myDoc = db.orders.findOne( { _id: ObjectId("50a8240b927d5d8b5891743c") } );
  2. map.apply(myDoc);
  • Verify the key and value pair is as you expected.
  1. emit
  2. key: abc123 value:250
  • Invoke the map function with multiple documents from the orderscollection:
  1. var myCursor = db.orders.find( { cust_id: "abc123" } );
  2.  
  3. while (myCursor.hasNext()) {
  4. var doc = myCursor.next();
  5. print ("document _id= " + tojson(doc._id));
  6. map.apply(doc);
  7. print();
  8. }
  • Verify the key and value pairs are as you expected.

See also

The map function must meet various requirements. For a list of allthe requirements for the map function, see mapReduce,or the mongo shell helper methoddb.collection.mapReduce().