D. Visser
D. Visser

Reputation: 923

How do I prevent Java's Mongo driver from escaping quotes in queries

The case

So I'm trying to execute a query to a Mongo database using Java. In shell, the query I'm talking about looks like this:

db.myCollection.find({ "array" : { "$in" : [ "foo" , "bar" ]}});

The query is put together in Java like so:

DBCursor cursor = myCollection.find(new BasicDBObject("array", new BasicDBObject("$in", items)));

Here, variable items is defined as a String[], which is passed from somewhere else. It can hold any value, but in this example it contains the following elements:

"foo", "bar";

The problem

This is where the problem starts. Calling

cursor.getQuery()

returns

{ "array" : { "$in" : [ "\"foo\"" , "\"bar\"" ]}}

which won't give back any results. As you can see, the Mongo driver for Java added quotes and escaped them.

I tried

  1. Copying the array, and making sure everything is trimmed off. Then pass it to the query.

    String[] test = new String[items.length];
    for(int i = 0; i < items.length; i++){
        test[i] = items[i].trim();
    }
    

    Didn't work.

  2. Now here's some real magic for y'all! I tried initializing the string just before the query like this:

    String[] items = new String[]{ "foo", "bar" };
    

    When I initialize it like that, Mongo doesn't escape the quotes and the query works.


So I'd like to know what kind of trickery this is. And how I could solve this.

Thank you all for reading!

Upvotes: 4

Views: 3387

Answers (2)

Davut G&#252;rb&#252;z
Davut G&#252;rb&#252;z

Reputation: 5746

Accepted answer is correct,

For the similar case I applied following trick, if anybody need a solution for quoted expressions I'm dropping below my solution.

BasicDBObject objectJsonKey = BasicDBObject.parse(quotedStrKey);
BasicDBObject filterCondition = new BasicDBObject("_id", objectJsonKey);

quotedStrKey is my compound json object _id with double quotes "

Upvotes: 0

Pawel Veselov
Pawel Veselov

Reputation: 4225

You shouldn't attempt to prevent Mongo driver from escaping the string literals. Escaping is done to ensure that the final json or bson is syntactically correct. AFAIK, it's not possible to alter how Mongo driver formats final messages to the server, which is reasonable since it's properly implementing server protocol.

In your particular case, your intent was to use string literals foo and bar, yet your data contained literals "foo" and "bar" instead, causing the logical problems you were observing.

Upvotes: 3

Related Questions