Masterstack8080
Masterstack8080

Reputation: 537

Pymongo/MongoDB - Upsert many?

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

Answers (1)

Dezzley
Dezzley

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

Related Questions