Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - escaping quotes while inserting record

Tags:

bash

mongodb

I have encountered a strange problem while I was trying to write a bash scritp to copy some data from one database to another.

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

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!!!

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.

like image 288
Liberat0r Avatar asked Mar 27 '14 16:03

Liberat0r


1 Answers

There's a JIRA ticket for this issue and it's fixed in 2.5.0.

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" }
like image 165
Anand Jayabalan Avatar answered Oct 07 '22 09:10

Anand Jayabalan