admin管理员组文章数量:1571774
Win10,MongoDB-4.2 中对命名不规范的集合的操作办法
最近在学习MongoDB的过程中,和小伙伴遇到了对命名不规范的集合删除或者修改等操时shell报错问题,记录一下解决方法。
命名不规范的集合名包括以数字开头、以特殊符号开头的集合名称,比如名称 “01”、“1” 、“1coll” 、"/coll" 等。
报错内容
这里以集合的删除操作为例:
>show collections
/coll
01
1
1coll
> db./coll.drop()
2022-03-22T00:53:52.370+0800 E QUERY [js] uncaught exception: SyntaxError: missing name after . operator :
@(shell):1:3
> db.01.drop()
2022-03-22T00:54:00.909+0800 E QUERY [js] uncaught exception: SyntaxError: unexpected token: numeric literal :
@(shell):1:2
> db.1coll.drop()
2022-03-22T00:54:05.330+0800 E QUERY [js] uncaught exception: SyntaxError: identifier starts immediately after numeric literal :
@(shell):1:2
可看到报错信息都是提示语法错误:[js] uncaught exception: SyntaxError: unexpected token: numeric literal 等。
不仅仅是drop,用update、insert、find的提示如出一辙。
解决办法
由于在shell中直接使用包含特殊符号或者数字开头的集合名称操作时会出现以上报错,可以通过其他手段来替代集合的名称。
1.使用getCollection(“集合名”)来替代集合名称
比如:
>db.getCollection("/coll").drop()
true
此方法对以上四种不规范命名的集合都有效,也是最简单、靠谱的方式,建议用该方法将集合重命名为规范的集合名称以便后续操作,比如:
db.getCollection("/coll").renameCollection("newname")
{ "ok" : 1 }
2.使用db.getCollectionNames()来获得特殊集合的名称
原理和方法1类似,语法有点区别。
可以通过db.getCollectionNames()
获得当前数据库下包含所有集合名称的数组
> db.getCollectionNames()
[ "/coll", "01", "1", "1coll" ]
根据数组元素的下标删除目标集合,比如要删除"/coll"这个集合,该集合对应的数组的下标为0,如下:
> db[db.getCollectionNames()[0]].drop()
true
这里有个邪门的事情,该方法可以正常删除"/coll" “01” "1coll"这类不规范的文档,但是删除名称为非0开头的数字的集合会报错,比如要删除名称为"1"的文档,结果如下:
> show collections
01
1
1coll
> db[db.getCollectionNames()[1]].drop()
2022-03-22T01:32:28.600+0800 E QUERY [js] uncaught exception: Error: drop failed: {
"ok" : 0,
"errmsg" : "collection name has invalid type double",
"code" : 73,
"codeName" : "InvalidNamespace"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DBCollection.prototype.drop@src/mongo/shell/collection.js:708:15
@(shell):1:1
所以此方法不能删除名称为非0开头的数字的集合。
3.使用Robo3T等图形化工具操作
该方法只要打开图形化工具用鼠标操作即可,可以正常进行删除、插入、重命名、查询等操作。
总结:为了避免出现命名不规范导致的后续麻烦,在此呼吁各位同学在创建数据库、集合以及文档的时候,要遵循各项命名规范。
方法1和方法2都是在网上参考其他老哥分享的博客而总结。
原文参考链接: 在前端遨游的蔺超 monkey_four
版权声明:本文标题:MongoDB:针对命名不规范的集合,在对集合操作时报错的解决办法 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1725429604a1022750.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论