0
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.

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. The _id always remain constant as long as the MongoABC instance is same. So how do we create an unique _id for every time we call insert_one()?

This error is specific to mongo servers running in Microsoft azure.

  • 1
    Can you show an example of the `json` object you are inserting? It appears you are using the [pymongo](https://pymongo.readthedocs.io/en/stable/tutorial.html?highlight=insert_one#inserting-a-document) driver. Which version are you using? – Matt Kneiser Aug 23 '22 at 14:58
  • @MattKneiser Upgrading the version to the latest helped with the solutions that weren't working before. Thank you. – Shashwat Swain Sep 12 '22 at 08:43

1 Answers1

0

You don't need to create id for mongo db. Once document is inserted, id is automatically generated. You can check id by this snippet.

obj = db[collection].insert_many(json)
print(obj.inserted_ids)