Home > Blockchain >  If i have data with the same _id when you insert_one in pymono, how do i update it?
If i have data with the same _id when you insert_one in pymono, how do i update it?

Time:03-23

I just started using pymongo. Then, I created a for loop to insert data into MongoDB. However, when the inserted data and the data in the existing MongoDB are the same ID, I want to update the data in the existing MongoDB. I don't know how to do this.

#in mongoDB
collection = [
    {"_id" : 1234 ,
     "like" : ["dog"]
    }, ... 
]

#in python
data = [
   { "_id" : 1234 ,
     "like" : ["cat"]
   }, ...
]

client = pymongo.MongoClient(host)
db = client[collection_name]
col = db[documents_name]


for i in data:
    col.insert_one(data)
    
# result in mongoDB
collection = [
    {"_id" : 1234 ,
     "like" : ["dog","cat"]
    }, ... 
]

CodePudding user response:

MongoDB inserts the objects with an ObjectID which becomes the primary identity of the inserted document. This is usually auto generated in the server to keep the uniqueness.

If you want to insert with your own custom ObjectId ( not recommended ) , then you need to pass the data with objectid reference in bson package instead of plain string. Like

{"_id":ObjectId("..."), ..}

And yes, your need is to update if exists, for that you need to use the version of upsert instead of insert.

  • Related