您需要使用bulkAPI并使用[]运算符动态构建查询。在>>> import pymongo
>>> client = pymongo.MongoClient()
>>> db = client.test
>>> collection = db.collection
>>> bulk = collection.initialize_ordered_bulk_op()
>>> count = 0
>>> for doc in collection.find({'data': {'$exists': True}}):
... for index, value in enumerate(doc['data']):
... inc = {}
... inc['data.'+str(index)] = 1
... bulk.find({'_id': doc['_id']}).update_one({'$inc': inc})
... count = count + 1
... if count % 150 == 0:
... bulk.execute() # Execute per 150 operations and re-init
... bulk = collection.initialize_ordered_bulk_op()
...
>>> if count > 0:
... bulk.execute() # clean up queues
...
{'writeErrors': [], 'writeConcernErrors': [], 'upserted': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 6, 'nModified': 6, 'nRemoved': 0}
>>> list(collection.find())
[{'data': [2, 3, 4, 5, 6, 7], '_id': ObjectId('565dc8ec8ec4081174f6161a')}]
>>>
也可以在shell中这样做:
^{pr2}$