首页 > 解决方案 > pymongo 查询现有集合

问题描述

我有一个数据库SensorReadings,其中包含一个MeterReadings使用另一个脚本填充的集合,因此该集合已经存在。

我正在设置一个脚本来查询MeterReadings集合。如下所示。

## Imports ##
import pymongo

## Variables ##
url = "mongodb://localhost:27017"

## getDBConnection ##
def getDBConnection():
    client = pymongo.MongoClient(url)
    db = client["SesnorReadings"]
    collection = db["MeterReadings"]
    readings = collection.find_one({})
    for res in readings:
      print(res)

readings正在返回一个None类型。我得到的确切错误如下所示。

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    conn = functions.getDBConnection()
  File "functions.py", line 19, in getDBConnection
    for res in readings:
TypeError: 'NoneType' object is not iterable

当我先添加一个插入语句然后使用该find_one方法进行查询时,它将创建一个SensorReadings包含集合的新数据库MeterReadings

## Imports ##
import pymongo

## Variables ##
url = "mongodb://localhost:27017"

## getDBConnection ##
def getDBConnection():
    client = pymongo.MongoClient(url)
    db = client["SesnorReadings"]
    collection = db["MeterReadings"]
    readings = collection.find_one({})
    mydict = { "name": "John", "address": "Highway 37" }
    x = collection.insert_one(mydict)
    for res in readings:
        print(res)

上面的代码返回:

_id
name
address
{'_id': ObjectId('5fc679dd439f1a27d0bb0c5e'), 'name': 'John', 'address': 'Highway 37'}

然而,在 Mongo 终端中,现在有两个SensorReading数据库。一个有正确的数据,一个有我刚刚使用上面的代码片段添加的数据。

> show dbs
SensorReadings  0.000GB
SesnorReadings  0.000GB
admin           0.000GB
config          0.000GB
local           0.000GB

我只想连接到SesnorReadings已经创建的数据库并查询其中的MeterReadings集合。

标签: pythondatabasemongodbpymongo

解决方案


find_one返回一份文件。用于find获取所有文档。

正如评论中指出的那样,您的收藏名称有错字。


推荐阅读