Map函数的问题排除


进入MongoDB中文手册(4.2版本)目录

map函数是JavaScript函数,可将关联或“映射”一个值与一个键,并在map-reduce操作期间发出键值对 。

注意
在4.2.1版本开始,MongoDB的不赞成map,reduce和finalize函数使用scope(即使用JavaScript的BSON类型15)。要限制变量的范围,请改用scope参数。

要验证map函数发出的键值对,请编写您自己的emit函数。
考虑一个包含以下原型文档的orders集合:

{
     _id: ObjectId("50a8240b927d5d8b5891743c"),
     cust_id: "abc123",
     ord_date: new Date("Oct 04, 2012"),
     status: 'A',
     price: 250,
     items: [ { sku: "mmm", qty: 5, price: 2.5 },
              { sku: "nnn", qty: 5, price: 2.5 } ]
}
  1. 定义将每个文档的price映射到cust_id并发出cust_id和price对的map函数:
var map = function() {
    emit(this.cust_id, this.price);
};
  1. 定义emit函数来打印键和值:
var emit = function(key, value) {
    print("emit");
    print("key: " + key + "  value: " + tojson(value));
}
  1. 使用orders集合中的单个文档调用map函数:
var myCursor = db.orders.find( { cust_id: "abc123" } );

while (myCursor.hasNext()) {
    var doc = myCursor.next();
    print ("document _id= " + tojson(doc._id));
    map.apply(doc);
    print();
}
  1. 验证键和值对是否符合预期。
emit
key: abc123 value:250
  1. 使用orders集合中的多个文档调用map函数:
var myCursor = db.orders.find( { cust_id: "abc123" } );

while (myCursor.hasNext()) {
    var doc = myCursor.next();
    print ("document _id= " + tojson(doc._id));
    map.apply(doc);
    print();
}
  1. 验证键和值对是否符合预期。

也可以看看

进入MongoDB中文手册(4.2版本)目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值