Search code examples
javamongodbsearchmorphia

Morphia embedded list of linked objects search criteria


I am using MongoDB and java-lib Morphia to deal with it.

I have a two classes:

class User {
   ...

   #Reference
   private List<Invoice> invoiceTransactions = new ArrayList<Invoice>();

   ...
}

class Invoice {
   ...

   User user;

   ...
}

When I create invoice I put it into the invoiceTransactions list

Now I have an Invoice object and my goal to find corresponding User if it does not contain this invoice inside the invoiceTransactions list.

That is what I wrote:

Invoice invoice = ...;

Query<User> query = (Query) dao.createQuery();
query.disableValidation().filter(Mapper.ID_KEY, u.getId());
List<Invoice> inv = new ArrayList<Invoice>();
inv.add(invoice);
query.criteria(User.INVOICE_TRANSACTIONS).hasNoneOf(inv);

That is the MongoDB log:

Wed Jul 18 19:03:09 [conn48] update dwh.UserImpl query: { _id: ObjectId('4ffbc8d
943b693ac766255f3'), InvoiceTransactions: { $nin: [ { className: "abc.InvoiceImpl", sum: 70.0, invoiceStatus: "NEW", creationDate:
new Date(1342627389037), _id: ObjectId('5006de3d022993ac397609c4'), guid: "4DEAB
CCE-63F9-1B0A-59F2-1135A83054B9", day: "2012.07.18", hour: "2012.07.18 19", minu
te: "2012.07.18 19:03" } ] } } update: { $set: { authId: "bla-bla" } } 0ms

You can see that Invoice object is processing not like reference but like embedded object. As a result I have that criteria firing even if the in fact invoiceTransactions contains Invoice.

So, my question is how to force morphia to look on the inv object as on reference not putting it into resulting query with all fields?


Solution

  • Okey, here is the answer:

    Key<Invoice> invoiceKey = dao.getDatastore().getKey(invoice);
    List<Key<Invoice>> invoiceKeyList = new ArrayList<Key<Invoice>>();
    invoiceKeyList.add(invoiceKey);
    query.criteria(User.INVOICE_TRANSACTIONS).hasNoneOf(invoiceKeyList);