python - 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
集合。
解决方案
find_one
返回一份文件。用于find
获取所有文档。
正如评论中指出的那样,您的收藏名称有错字。
推荐阅读
- node.js - Node.js“请求”库是否支持异步可迭代响应流?
- python - 我想从我的 csv 编写器(输出文件)中删除标题
- java - 元素不可见异常?在动态自动提示下拉菜单中 - Selenium - Java
- docker - Docker 运行到 kubernetes yaml
- ibm-watson - Watson 助手 - 拼写 | 更新数组
- jquery - jQuery 路线图 - 重新加载或刷新
- ag-grid - 在 Ag-grid 的单元格编辑中使用“保存”和“取消”按钮
- python - 如何使用 sklearn 按组运行多个单变量回归?
- javascript - 如何使用asp.net mvc显示来自多个表的数据并在jgGrid中显示为单行
- arrays - 使用用户定义的函数在 BigQuery 数据集中插入海量数据时如何优化性能