MongoDB 資料庫引用

來源:互聯網
上載者:User

標籤:

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": "w3cschoolcc"},   "contact": "987654321",   "dob": "01-01-1991",   "name": "Tom Benzamin"}

address DBRef 欄位指定了引用的地址文檔是在 address_home 集合下的 w3cschoolcc 資料庫,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"}

MongoDB 資料庫引用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.