[英]How to create a unique `_id` for each db.collection.insert_one(doc) in MongoDB running in Azure?
class MongoABC:
def __init__(self):
# all the variable initialisation
...
def insert_to_mongo(self, user_id, json):
self.db.collection.insert_one(json)
如果我創建MongoABC
的實例並多次調用insert_to_mongo
function ,則會在_id
上生成E11000 重復鍵錯誤。
它是實時執行的,因此以前制作插入文檔( json
)副本、更新插入或刪除此處建議的_id
的解決方案在這種情況下似乎不起作用。 只要MongoABC
實例相同, _id
始終保持不變。 那么我們如何在每次調用insert_one()
時創建一個唯一的_id
呢?
此錯誤特定於在 Microsoft azure 中運行的 mongo 服務器。
您不需要為 mongo db 創建 id。 插入文檔后,會自動生成 id。 您可以通過此代碼段檢查 id。
obj = db[collection].insert_many(json)
print(obj.inserted_ids)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.