MongoDB Python Codio将新文档添加到集合中

时间:2019-02-04 20:37:54

标签: python mongodb codio

因此,我应该使用Codio创建一个Python文件,该文件将为数据库“城市”中现有的MongoDB集合创建一个名为“检查”的新文档。 但这不能成功地将新文档添加到集合中。

Click here for image

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文件的方式。

Click here for image

运行Create.py之后,我做了db.inspections.find({“ id”:“ 0203-2019-ssp1”}),但它不存在。

Click here for image

1 个答案:

答案 0 :(得分:0)

AUTOMATIC是pymongo库 1

版本3.0及更高版本中不推荐使用的方法

理想情况下,您要使用pymongo.collection.Collection.save 2

pymongo.collection.Collection.insert_one