MongoDB 資料庫引用

MongoDB 資料庫引用

在上一章節MongoDB關係中我們提到了MongoDB的引用來規範資料結構文件。

MongoDB 引用有兩種:

  • 手動引用(Manual References)
  • DBRefs

DBRefs vs 手動引用

考慮這樣的一個場景,我們在不同的集合中 (address_home, address_office, address_mailing, 等)儲存不同的地址(住址,辦公室地址,郵件地址等)。

這樣,我們在呼叫不同地址時,也需要指定集合,一個文件從多個集合引用文件,我們應該使用 DBRefs。


使用 DBRefs

DBRef的形式:

{ $ref : , $id : , $db :  }

三個欄位表示的意義為:

  • $ref:集合名稱
  • $id:引用的id
  • $db:資料庫名稱,可選引數

以下例項中使用者資料文件使用了 DBRef, 欄位 address:

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

address DBRef 欄位指定了引用的地址文件是在 itread01 資料庫下的 address_home 集合,id 為 534009e4d852427820000002。

以下程式碼中,我們通過指定 $ref 引數(address_home 集合)來查詢集合中指定id的使用者地址資訊:

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

以上例項返回了 address_home 集合中的地址資料:

{
   "_id" : ObjectId("534009e4d852427820000002"),
   "building" : "22 A, Indiana Apt",
   "pincode" : 123456,
   "city" : "Los Angeles",
   "state" : "California"
}