踩到的 Mongodb key的坑

作者: 乾九二 | 来源:发表于2015-12-31 11:01 被阅读2294次

    今天服务器重启了,发现用户数据不能存档。查找后发现是由于用户数据里存在了这种类型的 map:{"a.b.c": 1 } ,在存档进mongodb时,由于服务器进行了一些处理,导致存档失败。
    正常情况下这种类型的key 是可以存储进数据库的,但是会发生事与愿违的事情:

    > db.test.findOne()
    { "_id" : ObjectId("528090797f6408479a607d61"), "hi" : "world" }
    >
    >
    > db.test.insert({ "a.b.c": 1 }) 
    2015-12-31T10:28:53.098+0800 E QUERY    Error: can't have . in field names [a.b.c]
        at Error (<anonymous>)
        at DBCollection._validateForStorage (src/mongo/shell/collection.js:157:19)
        at insert (src/mongo/shell/bulk_api.js:646:20)
        at DBCollection.insert (src/mongo/shell/collection.js:243:18)
        at (shell):1:9 at src/mongo/shell/collection.js:157
    >
    >
    > db.test.update({"hi":"world" },{$set:{ "a.b.c" : 1 }})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.test.findOne()
    {
            "_id" : ObjectId("528090797f6408479a607d61"),
            "hi" : "world",
            "a" : {
                    "b" : {
                            "c" : 1
                    }
            }
    }
    >
    >
    

    可以看到这里insert根本就出错,而update被解析错了。
    特意查了下MongoDB的文档,发现在MongoDB的key中不能使用的字符包括:

    Windows下:/ . " $ * < > : | ?
    Linux下:  / . " $
    

    MongoDB文档

    For MongoDB deployments running on Windows, MongoDB will not permit database names that include any of the following characters:
    /. "$*<>:|?
    Also, database names cannot contain the null character.
    Restrictions on Database Names for Unix and Linux Systems
    For MongoDB deployments running on Unix and Linux systems, MongoDB will not permit database names that include any of the following characters:
    /. "$
    Also, database names cannot contain the null character.

    相关文章

      网友评论

        本文标题:踩到的 Mongodb key的坑

        本文链接:https://www.haomeiwen.com/subject/pfnihttx.html