繁体   English   中英

如何为在 Azure 中运行的 MongoDB 中的每个 db.collection.insert_one(doc) 创建一个唯一的`_id`?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM