[SERVER-4431] mongo shell doesn't escape characters in strings correctly Created: 05/Dec/11  Updated: 09/Oct/16  Resolved: 22/Jul/12

Status: Closed
Project: Core Server
Component/s: Shell
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Daniel Pasette (Inactive) Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

mongo shell running under cygwin, although that shouldn't affect this


Issue Links:
Depends
Duplicate
is duplicated by SERVER-26536 Regex containing an escaped | pipe sy... Closed
Related
Backwards Compatibility: Fully Compatible
Operating System: ALL
Participants:

 Description   

Tried the following in the mongo shell

> use foo
switched to db foo
> db.f.save(

{"name":"c:\a\b\c"}

);
> db.f.save(

{"name":"c:\\a\\b\\c"}

);
> db.f.find();

{ "_id" : ObjectId("4edd38551252ee52efdc0ed3"), "name" : "c:a\bc" } { "_id" : ObjectId("4edd38621252ee52efdc0ed4"), "name" : "c:\\a\\b\\c" }

>

The handling of backslashes within strings does not seem to be consistent. The first example removes some of them without doing anything to the following characters. The second example fails to use "
" as an escape for '\'.



 Comments   
Comment by William Zola [ 03/Jul/12 ]

The issue is that the mongo shell helpfully re-quotes any string which contains backslashes when it prints it out. The data stored in MongoDB doesn't really have the double-backslashes, it's just printed that way.

> 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-quoted
> x.str;
\D\D\D\D\D     // but it's really not

Comment by Jeff Ozvold [ 05/Dec/11 ]

The behavior appears to be sane to me. In the first example, I would expect unrecognized escape sequences to be converted to the normal characters, such as '\a' to 'a'. . I would then expect 'a' to be returned to the shell as 'a'. With recognized escape sequences, like double-backslashes and '\b', I would expect JS to convert them to the normal character, as in double-backslashes to '\' and '\b' to backspace. Then, when displaying them, reconvert them back in to the corresponding escape sequences.

In the Mozilla Reference https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#String_Literals is the phrase:
For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

Also, if you just do normal JS vars, you get this output:

> var x = "c:\a\b\c";
> var y = "c:\\a\\b\\c";
> x.length
5
> y.length
8
> x.quote()
"c:a\bc"
> y.quote()
"c:\\a\\b\\c"

Generated at Thu Feb 08 03:05:58 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.