Nima
Nima

Reputation: 113

How to use $in operator in mongodb with two fields in java

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!

Upvotes: 1

Views: 4697

Answers (2)

Akhil
Akhil

Reputation: 1264

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);
    }

Upvotes: 4

chridam
chridam

Reputation: 103365

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);

Upvotes: 0

Related Questions