簡體   English   中英

MongoDB 查找獲取引用的對象 id 和建議以供參考

[英]MongoDB lookup get referenced object id and advice for reference

我正在使用 PyMongo 和 MongoDB 4.0.1。 例如,我將調用我的集合 User 和 Car。 所以我的用戶只能得到一輛車(一對一的關系)

User
----
_id : ObjectId("2b2543b24713ea82ce3ae21f")
Firstname : John
Lastname : Doe
Car : ObjectId("5b854bb806a77a06ce321f1f")

Car
----
_id : ObjectId("5b854bb806a77a06ce321f1f")
Model : Tesla Motor

當我做這個查詢時:

db.user.aggregate(
  {$unwind: "$car"},
  {$lookup: {
    from:"car",
    localField: "car",
    foreignField: "_id",
    as: "car"
   }}
)

輸出顯示 car 屬性將是一組帶有一個對象的汽車...

{ 
  "_id" : ObjectId("2b2543b24713ea82ce3ae21f"), 
  "firstname" : "John", 
  "lastname" : "Doe" , 
  "car" : [ { 
      "_id" : ObjectId("5b854bb806a77a06ce321f1f"), 
      "model" : "Tesla Motor"
   }] 
}

有可能只得到一個對象而不是數組嗎?

關於引用的另一個問題。 許多不同的用戶可以獲得同一輛車。 在 No SQL 數據庫中引用對象 ID 好還是在 User 集合中創建所有 car 字段更好? 因為我必須更新所有不同的數據。 例如,如果 Car 發生變化,我認為只更新 Car 集合中的一個文檔比更新用戶集合中的 50 行更容易。

你覺得我說得對嗎?

您需要在$lookup階段之后使用$unwind

db.user.aggregate([
  { "$lookup": {
    "from": "car",
    "localField": "car",
    "foreignField": "_id",
    "as": "car"
  }},
  { "$unwind": "$car" }
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM