gpt4 book ai didi

python - Insert_one 不存在这样的方法@ pymongo 3.7.2

转载 作者:行者123 更新时间:2023-12-01 08:48:54 26 4
gpt4 key购买 nike

我刚刚开始学习 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”。插入”

最佳答案

存在符合 pymongo 文档的 insert_one,服务器版本 >= 3.2...

用途是:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com