0

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.

neocorp
  • 569
  • 7
  • 20

1 Answers1

2

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\"");
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • When I've inserted, I've just simply pushed a List to DB, why do those quotes exists? – neocorp May 30 '16 at 22:26
  • @NiyaziErdogan How are those objects generated? – shmosel May 30 '16 at 22:27
  • I read them from a CSV file and add to a list without a single modification. – neocorp May 30 '16 at 22:29
  • 1
    @NiyaziErdogan There are a few problems with your code. For one thing, it will fail on strings containing commas. For another, it ignores the fact that CSV values can be [enclosed in quotes](https://tools.ietf.org/html/rfc4180#page-3). Use a proper [CSV parser](https://www.google.com/search?q=java%20csv%20parser) and your problems will go away. – shmosel May 30 '16 at 22:39
  • thank you for your suggestion and time @shmosel I'll approve your answer anyway. – neocorp May 30 '16 at 23:21