How to find records by foreign key (dbref) in morphia and mongodb?

1.4k views Asked by At

I have following entity:

class Linf {
     @Id
     ObjectId id;
     @Reference
     Denied denied;
}

I want to find all Linfs that have Denied object with certain id. How can I do this? Will this query employ indexes? I want to avoid full scan if possible.

Thanx.

2

There are 2 answers

0
Stepan Yakovenko On BEST ANSWER

This works for me:

    Denied d2 = new Denied();
    d2.id = new ObjectId("52b4709f423d856472c34fa1");

    List list = datastore
            .createQuery(Linf.class)
            .field("denied")
            .equal(d2).asList();
2
evanchooly On

If you don't have an index on "denied" it'll be a full collection scan either way but something like this should do it for you:

datastore.createQuery(Linf.class).field("denied").equal(new Key<Denied>(Denied.class, id)).fetch()