gpt4 book ai didi

python - MongoDB引用参数值

转载 作者:行者123 更新时间:2023-12-01 00:51:19 26 4
gpt4 key购买 nike

我有一个小型 mongo DB,我正在尝试编写代码来尊重文档中嵌入的参数(键)的值。

我在本地主机上有一个 mongo DB 服务器,并且能够成功地将 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" } } }

现在,我想引用这些参数中的数据。我想得到“level 2_1”中所有内容的回复。 #我所做的尝试如下...并且收到的错误低于此。

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”,但到目前为止还无法这样做。

我的希望是能够根据需要引用此结构中的数据。

最佳答案

您的过滤器应该有括号:

level_1_param_1 = collection.find({"level1": "level2_1"})

关于python - MongoDB引用参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56555135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com