MongoDB: query by @DBRef

若如初见. 提交于 2019-12-01 16:46:48

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/13361278/mongodb-query-by-dbref

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!