MongoDB - 在插入记录时转义引号

时间:2014-03-27 16:32:50

标签: bash mongodb

当我尝试编写一个bash scritp来将一些数据从一个数据库复制到另一个数据库时,我遇到了一个奇怪的问题。

为了简单起见,我将通过以下示例介绍问题:
假设我们有一个文件,其中mongo insert命令要在mongo client中执行。使用Bash,它将是:

cat file.json | mongo --verbose --host $HOST

这在我们在记录内容中使用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!!!

我的问题是,为mongo客户端转义引号的方法是什么(我正在使用MongoDB shell verions: 2.2.4)? 为什么当记录中有偶数引号时,脚本会成功,奇数会失败? 我将补充一点,没有错误消息。 Mongo只是默默地失败(即使使用--verbose)并且集合中没有新记录。

1 个答案:

答案 0 :(得分:4)

此问题有一个JIRA ticket,它已在2.5.0中修复。

现在,您可以在插入时使用unicode点进行双引号:

> db.foo.insert({ "field": "test \u0022 test" })
> db.foo.find()
{ "_id" : ObjectId("533455e563083f9b26efb5c2"), "field" : "test \" test" }
相关问题