0

I am trying to create an equivalant of the following SQL query:

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

I tried all sorts of options but I keep getting the following error:

falsecom.mongodb.MongoException: $or requires nonempty array

Does anyone know how to do this?

Thanks.

4
  • What exactly did you try out in Mongo when you got that exception? Commented Jun 18, 2012 at 17:05
  • What library are you using? What's the code of your query? Commented Jun 18, 2012 at 17:18
  • You may take inspiration from this [1]: stackoverflow.com/questions/10620771/… Commented Jun 18, 2012 at 17:59
  • Thanks a lot Ravi, it works using this approach! Commented Jun 18, 2012 at 18:52

1 Answer 1

2

You can use the QueryBuilder class to make the code a bit more readable:

    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());

This will print "2".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.