[英]PyMongo: Using $push to update an existing document with a reference to another document
我有球隊收藏和球員收藏。 我正在嘗試使用$ push將文檔從players集合中的team *集合中插入。
這是兩者的數據模型:
團隊:
{
"team_id": 1,
"team_name": team_name,
"general_manager": general_manager,
"players": [
]
}
玩家:
{
"_id": "5c076550c779ce4fa2d4c9fd"
"first_name": first_name,
"last_name": last_name,
}
這是我正在使用的代碼:
player = players.find_one({ "$and": [
{"first_name": first_name},
{"last_name": last_name}] })
teams.update(
{"team_name": team_name},
{"$push":
{"players": {
"$ref": "players",
"$id": player["_id"],
"$db": db
}}})
執行此操作時,出現以下錯誤消息:
pymongo.errors.WriteError:找到$ id字段,前面沒有$ ref,這是無效的。
我究竟做錯了什么? 提前致謝!
我簡化了您的查詢。 嘗試以下(注釋中的解釋)
//Locate the player record
player = players.find_one({"first_name": first_name,"last_name": last_name})
//push this into the "players" array of the team
teams.update_one({"team_name": team_name},
{"$push": {"players": player } }
)
我使用了update_one而不是update,因為我假設您只需要更新team集合中的一個文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.