I want to insert a subdocument in a document that I have in my mongoDB database. I want to retrieve with a find a subdoc and then to add something there. My code for retrieving the document is the following:
db = client['database']
col= db['database_values']
res = col.find({"user_id": "13245"}) //returns the document after user_id which begins with item_id
temp = {"item_id": {"11": {"first_process": [],"sec_process": [],}}}
res.update(temp) //this is not working
How can I insert the subdocument in the filtered json file returned after the find method with the res (cursor)? How am I going to add the temp_json to the res collection?
EDIT: I manage to add sub-documents by filtering the user_id. Now I want to do the same for the case of item_id. For the case of user_id:
collection.update_one({"user_id": "13245"},{"$set": {"Item.11.first_process": [], "Item.11.sec_process": []}})
How can I do the same for the case of user_id, to check if item_id exist (already did that) and if yes to just update the sub-sub-document:
collection.update_one({"user_id": "13245", "Item": {"11":{}}}, {"$set": {"string": "123"}}) // tried sth like that but did not work
My whole code is the following:
from pymongo import MongoClient
collection = db['database']
res = collection.find({"User": "123"})
if res.count() == 0:
print "zero"
dss_historical_json = {"User": "123", "Item": {"123456": {"process1": [],"process2": [],}}}
process1_json = {"timestamp": "21354879546213", "process1_value": 0.4, "state": {"B": 0.1, "F": 0.2, "E": 0.3}}
process2_json = {"timestamp": "11354879546213", "process2_value": 0.2, "performance": 0.8}
dss_historical_json["Item"][str(123456)]["process1"].append(process1_json)
dss_historical_json["Item"][str(123456)]["process2"].append(process2_json)
temp = db.historical_values
temp = db.historical_values
post_id = temp.insert_one(dss_historical_json).inserted_id
else:
for line in res:
counter = 0
for key in line["Item"].keys():
if line["Item"].keys()[counter] == "123469":
collection.update_one({"User": "123"}, {"$addToSet": {"Item.123469.process1": [{"timestamp": "213546879", "process1_value": 1,"state": {"B": 0.1, "F": 0.2, "E": 0.3}}],"Item.123469.process2": [{"timestamp": "11354879546213","process2_value": 0.2,"performance": 0.8}]}})
else:
collection.update_one({"User": "123"},{"$set": {"Item.123469.process1": [{"timestamp": "213546879", "process1_value": 1, "state": {"B": 0.1, "F": 0.2, "E": 0.3}}],
"Item.123469.process2": [{"timestamp": "11354879546213", "process2_value": 0.2, "performance": 0.8}]}})
counter = counter + 1
$setoperator in an update method ascollection.update_one({"user_id": "13245"}, {"$set": temp_json})resis acursortype object. your code should generate error. Also do you want to update the dictionary or update the document in database?collection.update_one({"user_id": "13245"}, {"$set": { "item_id.111111.first_process": [], "item_id.111111.sec_process": [] }})