MongoDB Morphia elemMatch API

2.1k views Asked by At

I'm trying to put this into morphia query :

db.woot.find({
    "bar.tables": {
        $elemMatch: {
            "tableId": {
                $in: [3,
                4]
            },
            "tab": {
                $gte: 20000
            }
        }
    }
})

So I have :

Query<Table> q
q.field("bar.table").hasThisElement()

And after this I don't know how to finish the query and still using FieldEnd which supports in(), gte() methods without writing whole query myself with BasicDBObjects.

Please help me transform above query to the nicest possible Morphia equivalent.

EDIT: bar.tables is an array so matching must be done with elemMatch or else it can match first condition from some element and the second condition from the other element, but only elements matching both conditions are valid.

2

There are 2 answers

3
xeraa On

I would try something like this:

Query<Table> query = mongoDataStore.find(Table.class)
  .field("bar.table.tableId").hasAnyOf(tableIdArrayList)
  .field("bar.table.tab").greaterThan(20000);

You'll probably need some custom query builder, where you can set some conditions and it will then put together the right query for you — at least that's our approach.

0
amarshall On

Morhpia now has elemMatch so you can execute your original query.

Query<Example> tableQuery = mongoDatastore.createQuery(Example.class)
             .disableValidation()
             .field("tableId").hasAnyOf(Arrays.asList(3, 4))
             .field("tab").greaterThanOrEq(20000);
Query<Table> query = getCDB().getDatastore()
            .createQuery(Table.class)
            .field("bar.table").elemMatch(tableQuery);

Something along these lines should work.