javajsonmongodbmongodb-querydbobject

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("data", "someName");
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("xyz", 1);
List cursor = collection.find(allQuery).toArray();

This is the collection returned from DB:

{ "_id" : { "$oid" : "574c780aa8268280d1b53162"} , "id" : 1 , "name" : "\"Some name\"" , "city" : "\"Ankara\"" , "country" : "\"Turkey\""}

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.


Solution

  • 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\"");