6

各郵便番号で見つけたレコードの数を数えようとしています。
私の MongoDB には、郵便番号が埋め込まれています。ドット表記を使用すると、a.res.z (住所は a、住居は res、zip は z) にあります。たとえば、これは問題なく機能します。

db.NY.count({'a.res.z' : '14120'})

しかし、map 関数を試してみると (Python で、PyMongo を使用しているため):

map = Code("function () {"
           "    emit(this.a.res.z, 1);"
           "}")

mapreduce を呼び出すと、次のエラーが発生します。

pymongo.errors.OperationFailure: db assertion failure, assertion: 'map invoke failed: JS Error: TypeError: this.a has no properties nofile_b:0', assertionCode: 9014

ドット表記は最上位 (例: 1 つのドット) で機能しますが、埋め込みでは機能しません。秘密は何ですか?

4

1 に答える 1

9

このエラーは、マップリデューシングしているオブジェクトの少なくとも1つ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
}

PyMongoの引数を使用するにはquery、キーワード引数として次のように設定できます。map_reduce(...)

于 2011-07-08T02:13:22.207 に答える