【问题标题】:pymongo Query Existing Collectionpymongo 查询现有集合
【发布时间】:2020-12-01 17:20:13
【问题描述】:

我有一个数据库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 数据库。一个有正确的数据,一个有我刚刚使用上面的 sn-p 添加的数据。

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

我只想连接到已经创建好的SesnorReadings数据库,查询里面的MeterReadings集合。

【问题讨论】:

  • 其中一个拼写错误SesnorReadings
  • 谢谢你,这是漫长的一天哈哈

标签: python database mongodb pymongo


【解决方案1】:

find_one 返回一个文档。使用find获取所有文档。

如 cmets 中所指出的,您的收藏名称有误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-13
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多