I have question regarding MongoDB search query. I have two parameters on which I have to search either "text" or "username" and some more parameters also there.
So the SQL query would be like this:
select * from tbl where place='pune' and (gender='male' or type='life') and (text='hi' or username='hi')
How would it be in MongoDB?
Right now I am able to search with just one parameter:
DBObject query = new BasicDBObject();
BasicDBList dbl = new BasicDBList();
if (cmodel.getGender() != null) {
if ("male".equals(cmodel.getGender().toLowerCase())) {
dbl.add(new BasicDBObject(CrushModel.COLUMN_GENDER, "male"));
} else if ("female".equals(cmodel.getGender().toLowerCase())) {
dbl.add(new BasicDBObject(CrushModel.COLUMN_GENDER, "female"));
} else {
dbl.add(new BasicDBObject(CrushModel.COLUMN_TYPE, "crush"));
}
dbl.add(new BasicDBObject(CrushModel.COLUMN_TYPE, "life"));
query.put("$or", dbl);
}
query.put("text", new BasicDBObject("$regex", String.format(".*((?i)%s).*", searchText)));
query.put(CrushModel.COLUMN_PLACE, new ObjectId(cmodel.getPlace().toString()));
DBCursor cursor = collection.find(query);
db.test.find( { $and : [ {gender : 'male' },
{ place :'pune'},{$or:[{text:/abc0/},{userName:/abc0/}, {type : 'life' }]}] } )
this is not working the way i want it.
there is one more field in table name "type" ,
for ex. if gender is male/female for which type is "normal" then i also want to show the type "life" here
It is only showing me the either or result like the entries of all gender:male or only the entries of type "life", I want to show both of them.
Its working
db.test.find( { $and : [ { place : 'pune'},{$or:[{text:/hi u r looking awesome 10/},{userName:/hi u r looking awesome 10/}]},{$or:[{gender : 'male' },{type:'life'}]}] } )
thanks @Disposer