我正在尝试创建以下 SQL 查询的等效项:
Select * from X where a like 'a%' OR b like 'a%'
我尝试了各种选项,但我不断收到以下错误:
falsecom.mongodb.MongoException: $or requires nonempty array
有谁知道如何做到这一点?
谢谢。
您可以使用 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”。