Reputation: 1295
I have a python dictionary that has RESULT= {'04BB30FC-5476-11DD-A31F-17FB9CFF4B22': [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}, {'4531': '0.44331446284643317'}
key = 04BB30FC-5476-11DD-A31F-17FB9CFF4B22 and [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}] are key values.
I have a document in mongoDB with same key and different key values.
collection = db["DOCUMENT"]
DOCUMENT={ "_id" : ObjectId("5d5270c4464cc8210eb5f683"), "ID" : "04BB30FC-5476-11DD-A31F-17FB9CFF4B22" : [ { "7173" : "0.4076433655407347" }, { "526" : "0.3878485824518719" }]
I want to do a check, if ID in result is found in document, it has to be updated else upsert=T.
for key in RESULT.keys():
print(key)
collection.update_one({"ID": key}, {"$set": RESULT}, upsert = True)
This code only inserts new data and fails to update but appends resulting in duplication.Please help.
Upvotes: 0
Views: 1186
Reputation: 8834
Your examples I'm afraid have some errors, however I suspect that you will need the $exists operator. With a bit of tidy up, the code below works.
collection =db['DOCUMENT']
# You are missing "])" from the end --- v
# RESULT = {'04BB30FC-5476-11DD-A31F-17FB9CFF4B22': [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}, {'4531': '0.44331446284643317'}
RESULT = {'04BB30FC-5476-11DD-A31F-17FB9CFF4B22': [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}, {'4531': '0.44331446284643317'}]}
# You have a "double colon" in your JSON which is invalid --- v v You are missing "})" from the end --- v
# db.document.insert_one({ "_id" : ObjectId("5d5270c4464cc8210eb5f683"), "ID" : "04BB30FC-5476-11DD-A31F-17FB9CFF4B22" : [ { "7173" : "0.4076433655407347" }, { "526" : "0.3878485824518719" }]
collection.insert_one({"04BB30FC-5476-11DD-A31F-17FB9CFF4B22" : [ { "7173" : "0.4076433655407347" }, { "526" : "0.3878485824518719" }]})
print(collection.find_one({}))
for key in RESULT.keys():
print(key)
collection.update_one({key: {"$exists": True}}, {"$set": RESULT}, upsert = True)
print(collection.find_one({}))
Upvotes: 2