python 读取mongodb,如何读取mongoDB中的所有集合?

如果我想读取我的数据数据库(mongoDB)的所有集合,我使用find()“print”方法(学院查找数据库())“我们出错了

错误:

“Database”对象不可调用。如果要对“MongoClient”对象调用“find”方法,则会失败,因为不存在此类方法。在

如何修复?

代码源:from pymongo import MongoClient

from pymongo import *

import os

import pprint

mongodb_host = 'localhost'

mongo_port = '27017'

client = MongoClient(mongodb_host + ':'+mongo_port)

db = client['test']

cl=db.client

try:

pprint.pprint(cl.find())

except Exception as e:

print ('this connection or insert are wrong.')

print (e)

错误:'Database' object is not callable. If you meant to call the 'find'

method on a 'MongoClient' object it is failing because no such method

exists.

如何修复它?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Python 操作 MongoDB 首先需要安装 pymongo 库。可以使用以下命令安装: ``` pip install pymongo ``` 接下来可以按照以下步骤从 MongoDB 表单读取两列数据并保存到两个 list : 1. 导入 pymongo 库。 ```python import pymongo ``` 2. 连接到 MongoDB 数据库。 ```python client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["mydatabase"] ``` 3. 选择要操作的集合。 ```python collection = db["mycollection"] ``` 4. 从集合读取两列数据并保存到两个 list 。 ```python column1 = [] column2 = [] for document in collection.find({}, {"_id": 0, "column1": 1, "column2": 1}): column1.append(document["column1"]) column2.append(document["column2"]) ``` 完整代码如下: ```python import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["mydatabase"] collection = db["mycollection"] column1 = [] column2 = [] for document in collection.find({}, {"_id": 0, "column1": 1, "column2": 1}): column1.append(document["column1"]) column2.append(document["column2"]) ``` 其,`mydatabase` 和 `mycollection` 分别为要操作的 MongoDB 数据库和集合的名称,`column1` 和 `column2` 分别为要读取的两列数据的名称。`find` 方法的第一个参数是查询条件,这里使用了一个空字典表示查询所有文档;第二个参数是要返回的字段,这里使用了一个字典指定返回 `column1` 和 `column2` 两列,并且排除 `_id` 字段。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值