Insert_one不存在此类方法@ pymongo 3.7.2

时间:2018-11-08 17:51:14

标签: python pymongo pymongo-3.x

我是学习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.one”。插入”

1 个答案:

答案 0 :(得分:1)

对于服务器版本> = 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