Niyazi Erdogan Niyazi Erdogan - 1 year ago 95
JSON Question

Java MongoDB cannot query with String criteria in collection

I have a collection in DB and can get it to a DBCollection just fine.
But when I try to query it with a String field, it doesn't return any result.

However, when I query with an Integer field, that query returns results for the same dataset.

Here are my trials:

// It doesn't work this way, cursor has nothing
DBObject allQuery = new BasicDBObject();
allQuery.put("iata", "BOS");
List cursor = collection.find(allQuery).toArray();

// This time it works, only change is that I query with an Integer value now
DBObject allQuery = new BasicDBObject();
allQuery.put("altitude", 19);
List cursor = collection.find(allQuery).toArray();

This is the collection returned from DB:

{ "_id" : { "$oid" : "574c780aa8268280d1b53162"} , "id" : 1 , "name" : "\"General Edward Lawrence Logan Intl\"" , "city" : "\"Boston\"" , "country" : "\"United States\"" , "iata" : "\"BOS\"" , "icao" : "\"KBOS\"" , "latitude" : 42.364347 , "longitude" : -71.005181 , "altitude" : 19 , "timezone" : -5 , "dst" : "\"A\""}

I suspect those String representations with "\" characters but couldn't find any workaround to it either.

I've checked dozens of articles and also MongoDB documentation but there seems to be nothing special about this. But interestingly it doesn't work.

Hope you can show me a way to get around this.
Thank you.


Your string values are enclosed in quotes. If you're not able to change that, you can include the quotes in your query:

allQuery.put("iata", "\"BOS\"");