我有一个具有集合MeterReadings的数据库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({})
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当我先添加一条insert语句,然后使用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集合。
发布于 2020-12-02 04:25:28
find_one返回一个文档。使用find获取所有文档。
而且,正如评论中指出的那样,您在集合名称中有一个拼写错误。
https://stackoverflow.com/questions/65095318
复制相似问题