我在尝试编写 bash scritp 以将一些数据从一个数据库复制到另一个数据库时遇到了一个奇怪的问题。
为简单起见,我将通过以下示例展示该问题:
假设我们有一个文件,其中包含要在mongo client
. 有了Bash
这将是:
cat file.json | mongo --verbose --host $HOST
Run Code Online (Sandbox Code Playgroud)
这工作正常,直到我们在记录内容中使用 qoutes。
例如:
use somedb;
db["collection"].insert({ "field": "test" })
#This of course works
db["collection"].insert({ "field": "test \" test" })
#But this doesn't
db["collection"].insert({ "field": "test \\" test" }) "#<-For syntax coloring
#I thounght maybe double quoting will help, but this also doesn't work
db["collection"].insert({ "field": "\"test\"" })
#This SUPRISINGLY works!!!
Run Code Online (Sandbox Code Playgroud)
我的问题是,为 mongo 客户端(我正在使用MongoDB shell verions: 2.2.4
)转义报价的正确方法是什么?为什么当记录中有偶数个引号时,脚本会成功而奇数会失败?我会补充一点,没有错误消息。Mongo
只是无声地失败(即使使用--verbose
)并且集合中没有出现新记录。
这个问题有一张JIRA 票,它在 2.5.0 中得到修复。
现在,您可以在插入时使用双引号的 unicode 点:
> db.foo.insert({ "field": "test \u0022 test" })
> db.foo.find()
{ "_id" : ObjectId("533455e563083f9b26efb5c2"), "field" : "test \" test" }
Run Code Online (Sandbox Code Playgroud)