踩到的 Mongodb key的坑

今天服务器重启了,发现用户数据不能存档。查找后发现是由于用户数据里存在了这种类型的 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.

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 12,221评论 0赞 23
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,879评论 5赞 6
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 3,067评论 0赞 0
  • 回宿舍发现侧门被锁了,改走正门,在小道上前面,有一个阿姨推着自行车,车上绑着些泡沫,泡沫从车上掉了下来,阿姨停住车...
    陈耿坤阅读 241评论 2赞 1
  • 一、觉察日记 【事实】两天的学习过程,不断的总结反思 【感觉】收获满满,很丰盛 【意图】不断的学习、成长、提升,达...
    以诗为名阅读 218评论 0赞 0

友情链接更多精彩内容