利用DBREF实现MongoDB的引用("外键")

Using DBRefs

There are three fields in DBRefs:

$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 name of the database in which the referenced document lies

Consider a sample user document having DBRef field address as shown below:

{
   "_id":ObjectId("53402597d852426020000002"),
   "address": {
   "$ref": "address_home",
   "$id": ObjectId("534009e4d852427820000002"),
   "$db": "tutorialspoint"},
   "contact": "987654321",
   "dob": "01-01-1991",
   "name": "Tom Benzamin"
}

The address DBRef field here specifies that the referenced address document lies in address_home collection under tutorialspoint database and has an id of 534009e4d852427820000002.

The following code dynamically looks in the collection specified by $refparameter (address_home in our case) for a document with id as specified by$id parameter in DBRef.

>var user = db.users.findOne({"name":"Tom Benzamin"})
>var dbRef = user.address
>db[dbRef.$ref].findOne({"_id":(dbRef.$id)})

The above code returns the following address document present inaddress_home collection:

{
   "_id" : ObjectId("534009e4d852427820000002"),
   "building" : "22 A, Indiana Apt",
   "pincode" : 123456,
   "city" : "Los Angeles",
   "state" : "California"
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
DBRefMongoDB中一种特殊的数据类型,用于在不同文档之间建立关联关系。它的全称是Database Reference,可以理解为数据库引用DBRef通常用于在两个文档之间建立关联,类似于关系型数据库中的。在一个文档中,可以使用DBRef类型字段引用另一个文档的_id字段。这个_id字段可以是内部文档的_id或者部文档的_id。使用DBRef可以省去在一个文档中存储另一个文档的所有字段的麻烦,同时也方便了文档之间的查询和更新操作。 在Java Spring Data MongoDB中,可以使用@DBRef注解来定义DBRef类型字段。例如: ```java public class Order { @Id private String id; private String name; @DBRef private User user; // getters and setters } public class User { @Id private String id; private String username; // getters and setters } ``` 在上面的例子中,Order类中的user字段是一个DBRef类型字段,它引用了User类的_id字段。使用@DBRef注解告诉Spring Data MongoDB这个字段是一个DBRef类型的字段。 当查询Order文档时,可以通过user字段的_id属性查询关联的User文档,例如: ```java Order order = mongoTemplate.findById("order_id", Order.class); User user = order.getUser(); String userId = user.getId(); User user = mongoTemplate.findById(userId, User.class); ``` 这个例子中,首先查询了一个Order文档,然后通过Order文档中的user字段的_id属性查询了关联的User文档。 需要注意的是,使用DBRef需要谨慎,因为它可能导致文档之间的循环引用,同时也会增加查询和存储的复杂性。因此,在使用DBRef时应该根据具体情况进行权衡和选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值