mongodb-java

How to check a String in a set (Find_IN_SET) using MongoDB Java


I am working on a web-services code in MongoDB using Java ,I have a table where one of the column contains range values like 1,2,3 or 3,4,5 or 6,7,8 . Given a value like 2 , I have to check whether the value lies in each of the specified ranges I tried the following query in MYSQL

select * from Table where FIND_IN_SET('2',RangeField)

and the java code i have tried is

BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("RangeField","2");
DBCursor cursor = col.find(whereQuery);

I don't have any idea about the right syntax to define find_in_set in Mongo Java. RangeField is String in table and its like 1,2,3 or 3f,5f. How to replicate the same in mondoDB java code

Thanks


Solution

  • You can use regex to get all the records which contains search string.

    In MongoDB :

    db.Table.find({"RangeField":{$regex:"2"}}); //List records which contain 2 anywhere
    

    In Java :

    BasicDBObject dbObject = new BasicDBObject();
    dbObject.put("RangeField",  java.util.regex.Pattern.compile("2"));
    try(DBCursor cursor = collection.find(dbObject))
    {
        while (cursor.hasNext())
        {
            System.out.println((BasicDBObject) cursor.next());
        }
    }