MongoDB 学习笔记之 DBRef

DBRef:

MongoDB建模有两种方式,一种是内嵌(Embed),另一种是连接(Link)。内嵌比较好理解,就是字段内容是个数组,数组内再包含文档,而我们今天介绍的是另一种,称为链接DBRef。由于MongoDB对单个文档(document)有大小16M限制,设计时也要将这个限制纳入考虑。

DBRef接收主要3个参数:

  • collection: 指定原始数据所在的集合
  • id: 指定引用文档的id
  • database: 指定所引用数据库的名称

示例:

创建people集合:

db.people.insert({name: "Sky", age: "20", "dep": "CSL"})
db.people.insert({name: "Bill", age: "22", "dep": "CSL"})

创建DBRef:

db.deps.insert({name: "CSL", num: 15, people: [ DBRef("people", ObjectId("59b51b36a36f6ee8c75b0f68"), "test"), DBRef("people", ObjectId("59b51b44a36f6ee8c75b0f69"), "test")]})

 

那么如何引用呢?

db.deps.findOne({"name": "CSL"}).people[0].fetch()

db.deps.findOne({"name": "CSL"}).people[1].fetch()

原文地址:https://www.cnblogs.com/AK47Sonic/p/7501930.html