Hi @Tuan_Dinh1 and welcome in the MongoDB Community
!
I wrote a little test in Python to see what I could do:
from pprint import pprint
from pymongo import MongoClient, ReplaceOne, ASCENDING
def init_mongodb():
global coll
client = MongoClient()
db = client.get_database('test')
coll = db.get_collection('coll')
if __name__ == '__main__':
init_mongodb()
# init content of collection for the example
coll.delete_many({})
coll.insert_many([
{'_id': 2, 'name': 'Not-Lauren'},
{'_id': 3, 'name': 'Not-Mark'}
])
print('Collection content BEFORE')
for doc in coll.find().sort('_id', ASCENDING):
print(doc)
bulk_ops = [
ReplaceOne({'_id': 1}, {'name': 'Max'}, upsert=True),
ReplaceOne({'_id': 2}, {'name': 'Lauren'}, upsert=True),
ReplaceOne({'_id': 3}, {'name': 'Mark'}, upsert=True)
]
bulk_result = coll.bulk_write(bulk_ops, ordered=True)
print('\nBulk Result')
pprint(bulk_result.bulk_api_result)
print('\nCollection content AFTER')
for doc in coll.find().sort('_id', ASCENDING):
print(doc)
Which prints:
Collection content BEFORE
{'_id': 2, 'name': 'Not-Lauren'}
{'_id': 3, 'name': 'Not-Mark'}
Bulk Result
{'nInserted': 0,
'nMatched': 2,
'nModified': 2,
'nRemoved': 0,
'nUpserted': 1,
'upserted': [{'_id': 1, 'index': 0}],
'writeConcernErrors': [],
'writeErrors': []}
Collection content AFTER
{'_id': 1, 'name': 'Max'}
{'_id': 2, 'name': 'Lauren'}
{'_id': 3, 'name': 'Mark'}
As you can see from the output I get from the bulk operations, I know that {_id: 1} was upserted and the 2 others found a matching document so they performed a replace operation.
I hope this helps.
Cheers,
Maxime.