Reputation: 1291
i have a field in mongodb in which documents starts with words like 1.1. , 2.0. , 2.1., 3.0.,3.1 etc. but i need to query documents that start with some specific string like 1.1.or 2.0. etc. i don't care what ever after this 1.1. or 2.0. or. i tried the query like this
BasicDBObject whereQuerylevel = new BasicDBObject();
whereQuerylevel.put("level",new BasicDBObject("$regex", "^1.1."));
myCollection.find(whereQuerylevel);
how do i get documents in a field which start with 1.1. or 2.0. something like that in mongodb?
Upvotes: 3
Views: 310
Reputation: 1883
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("level", new BasicDBObject("$regex", "^[1-9].[1-9]");
myCollection.find(regexQuery);
In case you need to limit the numbers in your criteria you can change the range inside the brackets. i.e. [1-9] will get you all the number between 1-9 if you want to limit it so the first number will be between 1-3 and the second number after the dot is only zero or 1 then you can change it to [1-3].[0-1]
I would warmly recommend reading into this regular expression interactive tutorial
Upvotes: 1