I have a mongodb collection in which "source_site_id" is my index. I have a dictionary of data which I would upsert on a timer. I currently have a field of "site_guid" which is empty for every record in my collection but would like to do a one time insert of it, generated through the uuid python library. Afterwards I would like to do an upsert. "site_guid" should not be changed unless it does not exist or we are inserting a new record. I currently have the code below but it looks like this whill change the "site_guid" every single time. What other options do I have?
for record, site_id in zip(data2, site_id_list):
record["site_id"] = site_id
record["site_guid"] = str(uuid.uuid4())
collection = MONGO_iconnect_dba_CONN["sites"]
upserts = [UpdateOne({"source_site_id": x["source_site_id"]}, {"$setOnInsert": x}, upsert=True) for x in data2]
result = collection.bulk_write(upserts)