在python中的mongoDB文档中插入json子文档

2024-09-27 02:20:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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

Tags: 文档idjsondbvalueupdateresfind

热门问题