|  | 
 
 发表于 2023-6-27 09:37:19
|
显示全部楼层 
| 你的报错信息显示  'Collection' object is not callable. If you meant to call the 'insert' method on a 'Collection' object it is failing because no such method exists. ,这是因为在较新的pymongo版本中, insert  方法已经被弃用,取而代之的是  insert_one  或  insert_many 。 
 你可以根据需要选择适合的方法。如果你只插入一条数据,可以使用  insert_one  方法;如果插入多条数据,可以使用  insert_many  方法。
 
 你的代码可以改写为如下:
 
 
 复制代码import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
student = {
    'id':'20170101',
    'name':'Jordan',
    'age':20,
    'gender':'male'
}
db = client.test
collection = db.students
result = collection.insert_one(student)
print(result.inserted_id)
 这段代码的最后一行会输出插入文档的  _id 。如果文档中没有提供  _id ,那么  insert_one()  会自动为其生成一个。
 
 如果你需要一次插入多条数据,可以这样写:
 
 
 复制代码import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
students = [
    {'id':'20170101', 'name':'Jordan', 'age':20, 'gender':'male'},
    {'id':'20170102', 'name':'Mike', 'age':21, 'gender':'male'}
]
db = client.test
collection = db.students
result = collection.insert_many(students)
print(result.inserted_ids)
 这段代码会输出所有插入文档的  _id  列表。
 | 
 |