Mass update in Pymongo using multiple ObjectId

I want to update thousands of documents in the mongo collection. I want to find them using ObjectId, and then, whatever the document is, needs to be updated. My update is the same for all documents. I have a list of ObjectId. For each ObjectId list in mongo should find the corresponding document and update the "isBad" key of this document to "N"

ids = [ObjectId('56ac9d3fa722f1029b75b128'), ObjectId('56ac8961a722f10249ad0ad1')]
bulk = db.testdata.initialize_unordered_bulk_op()
bulk.find( { '_id': ids} ).update( { '$set': {  "isBad" : "N" } } )
print bulk.execute()

This gives me the result:

{'nModified': 0, 'nUpserted': 0, 'nMatched': 0, 'writeErrors': [], 'upserted': [], 'writeConcernErrors': [], 'nRemoved': 0, 'nInserted': 0}

It is expected because it is trying to match "_id" with the list. But I do not know how to act.

I know how to update each document individually. My list size is about 25,000. I do not want to make 25,000 calls individually. The number of documents in my collection is much larger. I am using python2, pymongo = 3.2.1.

+4
2

. :

    bulk = db.testdata.initialize_unordered_bulk_op()
    for i in range (0, len(ids)):
        bulk.find( { '_id':  ids[i]}).update({ '$set': {  "isBad" : "N" }})
    print bulk.execute()
-1

for 500:

bulk = db.testdata.initialize_unordered_bulk_op()
counter = 0

for id in ids:
    # process in bulk
    bulk.find({ '_id': id }).update({ '$set': { 'isBad': 'N' } })
    counter += 1

    if (counter % 500 == 0):
        bulk.execute()
        bulk = db.testdata.initialize_ordered_bulk_op()

if (counter % 500 != 0):
    bulk.execute()

1000 ( docs), , 1000.

500 , , Bulk.find() BSON, , 1000 BSON 16 . Bulk() mongo .

+7

Source: https://habr.com/ru/post/1629360/


All Articles