Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't MongoDb store my slashes in this string?

Tags:

mongodb

Can anyone tell me why this command doesn't work from the MongoDB shell client:

db.coll.update({'live':true},{$set:{'mask':"\D\D\D\D\D\D\D\D"}},false,true)

but

db.coll.findOne({'id':'someId'})

returns the mask field as:

"mask" : "DDDDDDDD",

Where are the slashes going?

I've tried "double escaping" with \\D and that inserts both slashes:

"mask" : "\\D\\D\\D\\D\\D\\D\\D\\D",

MongoDB shell version: 2.0.6, MongoDB version: 2.0.5, OSX Lion

Thanks

like image 414
Rob Dudley Avatar asked Jul 03 '12 20:07

Rob Dudley


3 Answers

Actually, MongoDB does properly store the backslashes in the database. What you're seeing is an artifact of how the mongo shell displays strings which contain the backslash character. It will print them as escape sequences rather than as single characters. If you look at the actual data that comes back, you'll see that it's correct.

> db.tst.drop()
true
> db.tst.insert({ _id: 1, str: "\\D\\D\\D\\D\\D"} );
> x = db.tst.findOne( {_id:1} );
{ "_id" : 1, "str" : "\\D\\D\\D\\D\\D" }     // looks like it's double-backslashes
> x.str;
\D\D\D\D\D     // but it's really not
x.str.quote();
"\\D\\D\\D\\D\\D"   // it's what String.quote() prints
like image 89
William Z Avatar answered Nov 15 '22 09:11

William Z


use regex notation (without quotes)

/\D\D\D\D\D\D\D\D/ 

Or use four slashes.

"////D" ==> "/D"
like image 32
Mohsen Avatar answered Nov 15 '22 10:11

Mohsen


This is a case of *nix and C creeping into everything. In C, the character \ is the escape character. If allows you to "escape" the next character or characters to form some special character or character sequence. Thus, \n is newline (0x0a) and \d is carriage return (0x0d). So, since \ has this special meaning, in order to get a \ you have to have two of them.

Change your string to "\D\D\D\D\D\D\D\D"

like image 26
Wes Miller Avatar answered Nov 15 '22 10:11

Wes Miller