python - MongoDB Python Codio 向集合中添加新文档
问题描述
所以我应该使用 Codio 创建一个 Python 文件,该文件在数据库“city”中为现有的 MongoDB 集合创建一个名为“inspections”的新文档,但它没有成功地将新文档添加到集合中。
import json
from bson import json_util
from pymongo import MongoClient
connection = MongoClient('localhost', 27017)
db = connection['city']
collection = db['inspections']
def insert_document(document):
try:
result=collection.save(document)
except ValidationError as ve:
abort(400, str(ve))
return result
def main():
print "Hi"
myDocument = { "id" : "0203-2019-ssp1",
"certificate_number" : 5382334,
"business_name" : "BUILDING TO SERVE INC.",
"date" : "Jul 22 2015",
"result" : "Violation Issued",
"sector" : "Home Improvement Contractor - 100",
"address" : [ "city" : "JAMAICA", "zip" : 11432, "street" :
"HILLSIDE AVE", "number" : 17939 ] }
print insert_document(myDocument)
main()
这就是我在 Codio 终端中运行 Create.py 文件的方式。
运行 Create.py 后,我做了 db.inspections.find({"id":"0203-2019-ssp1"}) 但它不存在。
解决方案
pymongo.collection.Collection.save
是 pymongo 库1的 3.0 版及更高版本中不推荐使用的方法
理想情况下,您想使用pymongo.collection.Collection.insert_one
2
def insert_document(document):
try:
result=collection.insert_one(document)
except ValidationError as ve:
abort(400, str(ve))
return result
推荐阅读
- graphics - (GLSL)一个周末的光线追踪,如何将景深添加到视图矩阵?
- svelte - 有没有办法在 Sapper 路由中延迟加载动态导入?
- python-3.x - 什么是 KeyError:“twoColumnSearchResultsRenderer”(Python、youtube_dl)
- autohotkey - 将 gui 停靠到可变的活动窗口
- r - 将变量添加到 R 中的数据框并按所述变量排序
- reactjs - 如何在 ReactJs 中获取设备唯一 ID
- html - CSS/HTML:悬停图像,动画文本不起作用
- blazor - 当我有注册类型时,没有类型错误的注册服务
- node.js - nodejs 无法使用自动标头执行 http post
- css - 如何在包装的弹性项目之间实现分隔符?