此错误意味着您要减少地图的至少一个对象缺少res
其a
. 看:
> db.NY.find({}, {_id: 0})
{ "a" : { "res" : { "z" : 10011 } }, "name" : "alice" }
{ "a" : { "res" : { "z" : 10011 } }, "name" : "bob" }
{ "a" : { "res" : { "z" : 10012 } }, "name" : "carol" }
> m
function () {
emit(this.a.res.z, 1);
}
> r
function (key, values) {
var v = 0;
values.forEach(function (obj) {v += obj;});
return v;
}
> db.runCommand({mapreduce: "NY", map: m, reduce: r, out: {inline: 1}})
{
"results" : [
{
"_id" : 10011,
"value" : 2
},
{
"_id" : 10012,
"value" : 1
}
],
"timeMillis" : 0,
"counts" : {
"input" : 3,
"emit" : 3,
"output" : 2
},
"ok" : 1
}
> db.NY.insert({a: {}, name: "empty"})
> db.runCommand({mapreduce: "NY", map: m, reduce: r, out: {inline: 1}})
{
"assertion" : "map invoke failed: JS Error: TypeError: this.a.res has no properties nofile_b:1",
"assertionCode" : 9014,
"errmsg" : "db assertion failure",
"ok" : 0
}
您可以使用query
map-reduce 的参数来仅对具有所需字段的那些进行操作:
> db.runCommand({mapreduce: "NY", map: m, reduce: r, out: {inline: 1},
query: {"a.res.z": {$exists: true}}})
{
"results" : [
{
"_id" : 10011,
"value" : 2
},
{
"_id" : 10012,
"value" : 1
}
],
"timeMillis" : 1,
"counts" : {
"input" : 3,
"emit" : 3,
"output" : 2
},
"ok" : 1
}
要使用query
PyMongo 的参数,您可以将其设置为关键字参数map_reduce(...)