2017  Kodetalk | Feedback | Privacy Policy | Terms | About

Want to query mongodb with “like” same as relational DBMS?

I have a Collection in Mongodb with the name as "QUESTIONS" which contain all the question names with its suggested answers.

Now I want to find out all the questions which are contain "Java" similar to RDBMS like below,

select * from questions where question_name like "%Java%"

How I can construct the query the same in MongoDB ?


For MongoDB, to match regex with case insensitivity

You could use the following query

db.users.find ({ "name" : /m/i } ).pretty() 

The i in the /m/i indicates case insensitivity and .pretty() provides a more pretty output

For MongoDB Using Java, find the complete code snippet

MongoCollection<Document> dbCollection = MongoDBConnection.getDB().getCollection("CollectionName");
Document queryFilter = new Document();
queryFilter.put(FieldName,Pattern.compile("matched value"));
Map<String, Object> document = dbCollection.find(queryFilter).first();

Answer is