【问题标题】:MongoDB: query by @DBRefMongoDB:@DBRef 查询
【发布时间】:2012-11-01 21:55:26
【问题描述】:

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

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

    ...

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

@Document
public class WrappedA {
   @Id
   private String id;
   @DBRef
   private JetAnotherClass referenced;
   ...
}

“标签”字段的查询工作正常:

db.NotificationA.find( {"tag.$id": ObjectId("507b9902...32a")} )

但我需要查询 JetAnotherClass 的字段(两级 @DBRef 字段)。我尝试过使用点表示法和子对象,但它返回 null:

点符号:

db.NotificationA.findOne( {"tag.$referenced.$id": ObjectId("508a7701...29f")} )

子对象:

db.NotificationA.findOne( {"tag.$referenced": { "_id": ObjectId("508a7701...29f") }} )

有什么帮助吗? 提前致谢!

【问题讨论】:

    标签: mongodb dbref


    【解决方案1】:

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

    db.NotificationA.findOne({"tag.$id": ObjectId("blah")});
    

    但是:

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

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

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

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

    【讨论】:

    猜你喜欢
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2012-02-01
    • 2017-01-06
    相关资源
    最近更新 更多