MongoDB-插入记录时转义引号 [英] MongoDB - escaping quotes while inserting record
问题描述
当我尝试编写bash脚本以将一些数据从一个数据库复制到另一个数据库时,遇到了一个奇怪的问题.
I have encountered a strange problem while I was trying to write a bash scritp to copy some data from one database to another.
为简单起见,我将通过以下示例来介绍问题:
假设我们有一个文件,其中包含要在mongo client
中执行的mongo插入命令.对于Bash
,它将是:
To make things simple I will present the issue with the following example:
Let's say, we have a file in which are mongo insert commands that want to execute in mongo client
. With Bash
it will be:
cat file.json | mongo --verbose --host $HOST
这很好,直到我们在记录内容中使用qoutes为止.
例如:
This works fine until we use qoutes in records content.
For example:
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
也是如此),并且集合中没有新记录出现.
My question is, what is the propper way of escaping quotes for mongo client (I am using MongoDB shell verions: 2.2.4
)?
Why when there is an even number of quotes in record, the script will succeed and with odd number will fail?
I will add that, there are no error messages. Mongo
just fails silently(even with --verbose
) and no new records appears in collection.
推荐答案
有一个 JIRA票据此问题,已在2.5.0中修复.
There's a JIRA ticket for this issue and it's fixed in 2.5.0.
现在,您可以在插入时使用Unicode点将双引号引起来:
For now, you can use the unicode point for double quote when inserting:
> db.foo.insert({ "field": "test \u0022 test" })
> db.foo.find()
{ "_id" : ObjectId("533455e563083f9b26efb5c2"), "field" : "test \" test" }
这篇关于MongoDB-插入记录时转义引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!