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!
However, in cases where a document contains references from different collections, we can use MongoDB DBRefs.
$db − This is an optional field and contains the name of the database in which the referenced document lies Consider a sample user document having DBRef field address as shown in the code snippet −
MongoDB - Database References. As seen in the last chapter of MongoDB relationships, to implement a normalized database structure in MongoDB, we use the concept of Referenced Relationships also referred to as Manual References in which we manually store the referenced document's id inside other document.
$ref − This field specifies the collection of the referenced document $id − This field specifies the _id field of the referenced document $db − This is an optional field and contains the name of the database in which the referenced document lies Consider a sample user document having DBRef field address as shown in the code snippet −
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With