I have a class hierarchy designed for store user notifications:
@Document
public class Notification<T> {
@Id
private String id;
@DBRef
private T tag;
...
}
@Document
public class NotificationA extends Notification<WrappedA> {
}
@Document
public class NotificationB extends Notification<WrappedB> {
}
...
This is useful for returning polymorphic arrays, allowing me to store any kind of data in the "tag" field. The problem starts when the wrapped objects contains @DBRef fields:
@Document
public class WrappedA {
@Id
private String id;
@DBRef
private JetAnotherClass referenced;
...
}
Queries on the fields of "tag" works fine:
db.NotificationA.find( {"tag.$id": ObjectId("507b9902...32a")} )
But I need to query on the fields of JetAnotherClass (two levels of @DBRef fields). I've tried with dot notation and also with subobjects but it returns null:
Dot notation:
db.NotificationA.findOne( {"tag.$referenced.$id": ObjectId("508a7701...29f")} )
Subobjects:
db.NotificationA.findOne( {"tag.$referenced": { "_id": ObjectId("508a7701...29f") }} )
Any help? Thanks in advance!
Since you look like you are only querying by _id
I believe you can do:
db.NotificationA.findOne({"tag.$id": ObjectId("blah")});
However:
But I need to query on the fields of JetAnotherClass (two levels of @DBRef fields).
DBRefs are not JOINs, they are merely a self describing _id
in the event that you do not know the linking collection it will create a helper object so you don't have to code this yourself on the client side.
You can find more on DBRefs here: http://docs.mongodb.org/manual/applications/database-references/
Basically you can query the sub fields within the DBRef from the same document, i.e.: DBRef.$_id
but you cannot, server-side, resolve that DBRef and query on the resulting fields.