Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何通过Python在Mongo对象中插入数据_Python_Mongodb_Pymongo - Fatal编程技术网

如何通过Python在Mongo对象中插入数据

如何通过Python在Mongo对象中插入数据,python,mongodb,pymongo,Python,Mongodb,Pymongo,在费用集合中,我有一个Json: { "_id" : ObjectId("5ad0870d2602ff20497b71b8"), "Hotel" : {} } 如果可能的话,我想使用Python在Hotel中插入一个文档或另一个对象 我的Python代码: from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client['db'] collection_expenses = db ['ex

在费用集合中,我有一个Json:

{
"_id" : ObjectId("5ad0870d2602ff20497b71b8"),
"Hotel" : {}
}
如果可能的话,我想使用Python在
Hotel
中插入一个文档或另一个对象

我的Python代码:

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['db']
collection_expenses = db ['expenses']
#insert
d = int(input('Insert how many days did you stay?: '))
founded_expenses = collection_expenses.insert_one({'days':d})
上面的代码将文档插入集合中。我应该更改什么来添加de Hotel对象内的天数?
提前感谢。

您可能想看看
save
方法,而不是使用
insert\u one
,这是一种更宽松的方法

承认您的文档已在集合中创建:

[...]
expenses = db['expenses']

# Find your document
expense = expense.find_one({})

expense["Hotel"] = { "days": d }

# This will either update or save as a new document the expense dict,
# depending on whether or not it already has an _id parameter
expenses.save(expense)
知道
find_one
将返回您
None
如果不存在此类文档,您可能需要向上插入文档。因此,您可以使用
save
轻松地执行此操作