我对MongoDB搜索查询有疑问。我有两个参数,我必须搜索" text"或"用户名"还有一些参数。
所以SQL查询会是这样的:
select * from tbl where place='pune' and (gender='male' or type='life') and (text='hi' or username='hi')
如何在MongoDB中使用?
现在我只能使用一个参数进行搜索:
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' }]}] } )
这不是我想要的方式。
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.
它的工作
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'}]}] } )
感谢@Disposer
答案 0 :(得分:3)
mongo查询正是:
db.test.find( { $and : [ { gender : 'male' }, { place : 'pune' }, { $or : [ { text : 'hi' }, { username : 'hi' } ] } ] } )
java将是:
ArrayList orList = new ArrayList();
ArrayList andList = new ArrayList();
orList.add(new BasicDBObject("text", "hi"));
orList.add(new BasicDBObject("username", "hi"));
andList.add(new BasicDBObject("gender", "male"));
andList.add(new BasicDBObject("place", "pune"));
andList.add(new BasicDBObject("$and", orList));
BasicDBObject query = new BasicDBObject("$or", andList);
答案 1 :(得分:0)
使用MongoDB Java Driver v3.2.2执行上述操作的快捷方式。你可以这样做:
FindIterable<Document> iterable = collection.find(Document.parse("{$and: [{gender: 'male'}, {place: 'pune' }, {$or: [{text: 'hi'}, {username: 'hi'}]}]}"));
这应该返回与上面相同的结果。