【问题标题】:Insert_one no such method exists @ pymongo 3.7.2Insert_one 不存在这样的方法@ pymongo 3.7.2
【发布时间】:2019-04-12 07:12:15
【问题描述】:

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

【问题讨论】:

    标签: python pymongo pymongo-3.x


    【解决方案1】:

    insert_one 符合 pymongo 文档,服务器版本 >= 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

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      相关资源
      最近更新 更多