我有一个小的mongo DB,并且我正在尝试编写代码,该代码将尊重文档中嵌入的参数(键)的值。
我在本地主机上有一个mongo数据库服务器,并且能够将json格式的数据结构成功输入到我的数据库中。但是,当我尝试在其中引用此数据的值时,出现如下所示的错误。
import pymongo
import json
import time
from datetime import datetime
server = pymongo.MongoClient('localhost')
database = server['testData']
collection = database['testCollection']
test_entry1 = '{"Level1" : {"level2_1" : {"param1" : "1.6","param2" : "32.3","param3" : "11.0"}, "level2_2" : {"param1" : "2.6","param2" : "9.3","param3" : "112.0"}}}'
mongo_import = json.loads(test_entry1)
collection.insert_one(mongo_import)
上面的方法工作正常,当我查询数据库时,得到以下响应(按预期):
{ "_id" : ObjectId("5d0081e931775cbc28cf7704"), "Level1" : { "level2_1" : { "param1" : "1.6", "param2" : "32.3", "param3" : "11.0" }, "level2_2" : { "param1" : "2.6", "param2" : "9.3", "param3" : "112.0" } } }
现在,我想在这些参数中引用数据。我想对“ 2_1级”中的所有内容都做出回应。 #I的尝试在下面...并且收到的错误在下面。
level_1_param_1 = collection.find("level1" : "level2_1")
错误:
File "Desktop/Scripts/StackOverflowSnippit.py", line 29, in <module>
level_1_param_1 = collection.find('"level1" : "level2_1"')
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymongo/collection.py", line 1456, in find
return Cursor(self, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymongo/cursor.py", line 146, in __init__
validate_is_mapping("filter", spec)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymongo/common.py", line 452, in validate_is_mapping
"collections.Mapping" % (option,))
TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping
我还希望能够获得比“ level1-> level2_1-> param2”低一层的参数的值,但到目前为止,还无法做到这一点。
我希望能够根据需要引用此结构中的数据。
答案 0 :(得分:2)
您的过滤器应带有方括号:
level_1_param_1 = collection.find({"level1": "level2_1"})