MongoDB和JAVA - 带有Regex查询的逻辑OR

时间:2012-06-18 17:03:03

标签: java mongodb

我正在尝试创建以下SQL查询的等效项:

Select * from X where a like 'a%' OR b like 'a%'

我尝试了各种选项,但我不断收到以下错误:

falsecom.mongodb.MongoException: $or requires nonempty array

有谁知道怎么做?

感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用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”。