我是学习Python和所有包含内容的新手。
我试图迈出第一步,安装一个MongoDB(正在运行)并连接到它。
from pymongo import MongoClient
from pprint import pprint
from random import randint
client = MongoClient('localhost', 27017)
db = client.test
collection = db.users
user = {"id": 1, "username": "Test"}
user_id = collection.insert_one(user).inserted_id
print(user_id)
这是完整的代码。
pymongo版本:3.7.2检查:
pip freeze | grep pymongo
Output: pymongo==3.7.2
python版本:3.7.1
如果我尝试执行我的小脚本,则会发生以下错误:
'Collection' object is not callable.
If you meant to call the 'insert_one' method on a 'Collection'
object it is
failing because no such method exists.
我的错在哪里?
一项小小的研究表明,在pymongo v2中,“。insert_one”为“ .insert”,但是安装了3.7.2版本,因此我(必须)使用“ .insert.one”,而不是“ .insert”。
最佳答案
服务器版本> = 3.2时存在与pymongo文档一致的insert_one ...
用途是:
user = {'x': 1}
result = db.test.insert_one(user)
result.inserted_id
关于insert_one的更完整的解释:
>>> db.test.count_documents({'x': 1})
0
>>> result = db.test.insert_one({'x': 1})
>>> result.inserted_id
ObjectId('54f112defba522406c9cc208')
>>> db.test.find_one({'x': 1})
{u'x': 1, u'_id': ObjectId('54f112defba522406c9cc208')}
以下内容,我执行并正常工作:
# importing client mongo to make the connection
from pymongo import MongoClient
print("--- Exemplo pymongo Connection ---")
# Connection to MongoDB
client = MongoClient('localhost', 27017)
# Selection the Database
db = client.python
# Select the collection
collection = db.users
# Set up a document
user = {"id": 1, "username": "Test"}
# insert one document into selected document
result = collection.insert_one(user)
# Selection just one document from collection
#result = collection.find_one()
# removing the document inserted
collection.delete_one(user)
# print the inserted_id
print("inserted_id: ", result.inserted_id)
Pymongo Documentation
关于python - Insert_one没有这样的方法@ pymongo 3.7.2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53213476/