我有一个数据库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)
CCD_ 4正在返回CCD_。我得到的确切错误如下所示。
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
获取所有文档。
正如评论中所指出的,你在收藏名称上有一个拼写错误。