MongoDB:@DBRef查询

Roi*_*Roi 6 mongodb dbref

我有一个为商店用户通知设计的类层次结构:

@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> {
}

    ...
Run Code Online (Sandbox Code Playgroud)

这对于返回多态数组很有用,允许我在"tag"字段中存储任何类型的数据.当包装的对象包含@DBRef字段时,问题开始:

@Document
public class WrappedA {
   @Id
   private String id;
   @DBRef
   private JetAnotherClass referenced;
   ...
}
Run Code Online (Sandbox Code Playgroud)

对"tag"字段的查询工作正常:

db.NotificationA.find( {"tag.$id": ObjectId("507b9902...32a")} )
Run Code Online (Sandbox Code Playgroud)

但我需要查询JetAnotherClass的字段(两个级别的@DBRef字段).我尝试过点符号和子对象,但它返回null:

点符号:

db.NotificationA.findOne( {"tag.$referenced.$id": ObjectId("508a7701...29f")} )
Run Code Online (Sandbox Code Playgroud)

子对象:

db.NotificationA.findOne( {"tag.$referenced": { "_id": ObjectId("508a7701...29f") }} )
Run Code Online (Sandbox Code Playgroud)

有帮助吗?提前致谢!

Sam*_*aye 7

既然你看起来只是在查询,_id我相信你可以做到:

db.NotificationA.findOne({"tag.$id": ObjectId("blah")});
Run Code Online (Sandbox Code Playgroud)

然而:

但我需要查询JetAnotherClass的字段(两个级别的@DBRef字段).

DBRefs不是JOIN,它们只是一个自我描述_id,如果您不知道链接集合,它将创建一个帮助对象,因此您不必在客户端自己编写代码.

您可以在此处找到有关DBRefs的更多信息:http://docs.mongodb.org/manual/applications/database-references/

基本上,您可以从同一文档中查询DBRef中的子字段,即:DBRef.$_id但是您不能在服务器端解析该DBRef并在结果字段上进行查询.