简体   繁体   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)

If I create an instance of MongoABC and call the insert_to_mongo function more than once, it generates a E11000 duplicate key error on the _id .如果我创建MongoABC的实例并多次调用insert_to_mongo function ,则会在_id上生成E11000 重复键错误

It performs it in real time so previous solutions of making a copy of inserting document( json ), upserting it or deleting the _id as suggested here doesn't seem to work in this case.它是实时执行的,因此以前制作插入文档( json )副本、更新插入或删除此处建议的_id的解决方案在这种情况下似乎不起作用。 The _id always remain constant as long as the MongoABC instance is same.只要MongoABC实例相同, _id始终保持不变。 So how do we create an unique _id for every time we call insert_one() ?那么我们如何在每次调用insert_one()时创建一个唯一的_id呢?

This error is specific to mongo servers running in Microsoft azure.此错误特定于在 Microsoft azure 中运行的 mongo 服务器。

You don't need to create id for mongo db.您不需要为 mongo db 创建 id。 Once document is inserted, id is automatically generated.插入文档后,会自动生成 id。 You can check id by this snippet.您可以通过此代码段检查 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