1

I would like to retrieve the following information:

select names from database where address like 'colombo' and age>20;

but for MongoDB in Java. Essentially, it should return all names that contain the word colombo ang age greater than 20 in them. I know that there is the $in operator in MongoDB, but how do I do the same in Java, using the Java driver? I've been trying to look for it everywhere but am getting nothing. I've tried:

query = new BasicDBObject("names", new BasicDBObject("$in", "colombo"), new BasicDBObject("age", "$gt20"));

But it didn't worked :( Please help!

1
  • 1
    $in is used when you are checking if the value lies "IN" the given range. as per your requirement you don't need it. you need AND operator Commented May 20, 2016 at 12:30

2 Answers 2

4

Try this

BasicDBObject query = new BasicDBObject("names", new BasicDBObject("$in",      Arrays.asList("colombo")));
    query.append("age", new BasicDBObject("$gt", 20));
    FindIterable<Document> find = collection.find(query);
    MongoCursor<Document> iterator = find.iterator();
    Document doc = null;
    while (iterator.hasNext()) {
        doc = iterator.next();
        System.out.println(doc);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Somehow this answer does not work for me.. I am using OpenJDK 11 with mongo-java-driver -> version 3.12.5
0

The $in operator will not be suitable for such as you can only use it to match values that are in an array or to search for documents where the value of a field equals any value in a specified array.

In your case you need a $regex operator to fulfil the query by performing a SQL LIKE operation:

db.collection.find({
    "names": { "$regex": /colombo/, "$options": "i" },
    "age": { "$gt": 20 }
})

or

db.collection.find({
    "names": /colombo/i },
    "age": { "$gt": 20 }
})

which can be implemented in Java as

Pattern pattern = Pattern.compile("colombo", Pattern.CASE_INSENSITIVE);

BasicDBObject query = new BasicDBObject("names", pattern)        
    .append("$age", new BasicDBObject("$gt", 20));
DBCursor result = coll.find(query);

If using the 3.0.x and newer drivers:

Document regx = new Document();
regx.append("$regex", "(?)" + Pattern.quote("colombo"));
regx.append("$options", "i");

Document query = new Document("names", regx).append("$age", new Document("$gt", 20));
FindIterable<Document> iterable = db.getCollection("coll").find(query);

1 Comment

Thank you very much, it helped me to solve the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.