Stepan Yakovenko
Stepan Yakovenko

Reputation: 9206

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

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.

Upvotes: 2

Views: 1427

Answers (2)

Stepan Yakovenko
Stepan Yakovenko

Reputation: 9206

This works for me:

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

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

Upvotes: 1

evanchooly
evanchooly

Reputation: 6233

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

Upvotes: 1

Related Questions