问题代码
import pymongo
if __name__ == "__main__":
client = pymongo.MongoClient(host='127.0.0.1', port=27017, username='root', password='admin', authSource='test')
# 读取cs数据库
collection = client['cs']
#输出数据库名字
print(collection.name)
#新建插入数据
student_data = {
'id': '20170101',
'name': '张三',
'age': '20',
'gender': '2年级7班'
}
#数据插入
res=collection.insert_one(student_data)
问题报错
Traceback (most recent call last):
File "C:/Users/x/PycharmProjects/dabao/Mongodb/test.py", line 13, in <module>
cs_1
collection.insert_one(student)
File "C:\Users\x\AppData\Roaming\Python\Python38\site-packages\pymongo\collection.py", line 3486, in __call__
raise TypeError("'Collection' object is not callable. If you "
TypeError: 'Collection' object is not callable. If you meant to call the 'insert_one' method on a 'Database' object it is failing because no such method exists.
问题截图
问题解决:
我直接想砸电脑,网上有些教程分明写的就是错的,有些人还一直抄导致一传十十传百,真是气死人了这里纠正一下错误!
import pymongo
if __name__ == "__main__":
#改动1
client = pymongo.MongoClient("mongodb://localhost:27017")
# 读取cs数据库,没有的话就会自动建立
db = client['cs']
#输出数据库名字
print(db.name)
#注意!!!!集合名,没有的话就会自动建立
collection=db['student']
#新建插入数据
student_data = {
'id': '20170101',
'name': '张三',
'age': '20',
'gender': '2年级7班'
}
#数据插入
res=collection.insert_one(student_data)
OK,问题解决