Reputation: 537
I want to upsert the below data into a mongodb collection. If there is a document with an existing "id_number"
I want to upsert data if anything has changed. If the "id_number"
does not exist I want to create a new document. What is the most efficient way to do this using Python Pymongo? I have about 90,000 documents already existing in mongodb.
data = [
{"name": "John", "id_number":1, "age": "20"},
{"name": "Bob", "id_number":2, "age": 19}
]
Upvotes: 0
Views: 272
Reputation: 1855
I think you could perform bulk updateOne
operations with the upsert
flag.
Refer to the documentation for more info: https://www.mongodb.com/docs/manual/core/bulk-write-operations
Query sample:
db.characters.bulkWrite(
[
{ updateOne :
{
"filter" : { "id_number" : 1 },
"update" : { $set : { "name" : "John", "age" : "20" } },
"upsert" : true
}
},
{ updateOne :
{
"filter" : { "id_number" : 2 },
"update" : { $set : { "name" : "Bob", "age" : "19" } },
"upsert" : true
}
},
...
]
);
Upvotes: 1