可以使用QueryBuilder的類使代碼有點更具可讀性:
Mongo m = new Mongo();
m.setWriteConcern(WriteConcern.SAFE);
DBCollection c = m.getDB("test").getCollection("or-test");
c.drop();
c.insert(new BasicDBObject("a", "abba"));
c.insert(new BasicDBObject("b", "abba"));
c.insert(new BasicDBObject("a", "bbba"));
c.insert(new BasicDBObject("b", "bbba"));
Pattern pattern = Pattern.compile("^a");
DBObject query = QueryBuilder.start().or(
QueryBuilder.start("a").regex(pattern).get(),
QueryBuilder.start("b").regex(pattern).get()
).get();
System.out.println(c.find(query).count());
這將打印「2」。
當你遇到異常情況時,你究竟在Mongo中試過了什麼? – jsalonen
你在使用什麼庫?你的查詢的代碼是什麼? – toniedzwiedz
您可以採取的靈感來自這個 [1]:http://stackoverflow.com/questions/10620771/how-to-or-few-conditions-in-mongodb-using-java-driver/10620972#10620972 –