我想在mongoDB数据库中的文档中插入子文档。我想用find a subdoc检索,然后在那里添加一些东西。我检索文档的代码如下:
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
如何将子文档插入到经过筛选的json文件中,并在find方法后返回res(cursor)?如何将temp_json添加到res集合?在
编辑:我通过过滤用户标识来添加子文档。现在,我想对项目编号的情况进行同样的操作。对于用户编号:
^{pr2}$对于用户_id,我如何做同样的操作,以检查项_id是否存在(已经存在),如果存在,则仅更新子文档:
collection.update_one({"user_id": "13245", "Item": {"11":{}}}, {"$set": {"string": "123"}}) // tried sth like that but did not work
我的全部代码如下:
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
试试这个:
我可以理解您的问题,您需要插入多个
^{pr2}$item_id
。你可以这样做:检查插入嵌入文档的文档:Set Fields in Embedded Documents
相关问题 更多 >
编程相关推荐