【发布时间】:2017-05-03 08:21:36
【问题描述】:
我想在我的 mongoDB 数据库中的文档中插入一个子文档。我想通过查找子文档进行检索,然后在其中添加一些内容。我检索文档的代码如下:
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
如何将子文档插入到带有 res(光标)的 find 方法返回的过滤后的 json 文件中?我如何将 temp_json 添加到 res 集合中?
编辑:我设法通过过滤 user_id 添加子文档。现在我想对 item_id 的情况做同样的事情。对于user_id的情况:
collection.update_one({"user_id": "13245"},{"$set": {"Item.11.first_process": [], "Item.11.sec_process": []}})
对于 user_id 的情况,我该如何做同样的事情,以检查 item_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
【问题讨论】:
-
在更新方法中使用
$set运算符作为collection.update_one({"user_id": "13245"}, {"$set": temp_json}) -
我试过了,但 json 保持不变。没有添加任何内容。
-
实际上它是通过更新 item_id 的值来工作的。我想要的是保留以前的和新的。
-
您的问题不清楚。
res是一个cursor类型的对象。您的代码应该会产生错误。您还想更新字典还是更新数据库中的文档? -
试试
collection.update_one({"user_id": "13245"}, {"$set": { "item_id.111111.first_process": [], "item_id.111111.sec_process": [] }})