如何通过Python在Mongo对象中插入数据
在费用集合中,我有一个Json:如何通过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
{
"_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
轻松地执行此操作