Python 使用mongoDB和pymongo查询嵌套字典中的数组
我有一本这样的字典:Python 使用mongoDB和pymongo查询嵌套字典中的数组,python,mongodb,dictionary,pymongo,nested-lists,Python,Mongodb,Dictionary,Pymongo,Nested Lists,我有一本这样的字典: dici = { "city": { "coord": { "lat": 123123123, "lon": 123123 }, "country": "asdsd", "id": 2735943, "name": "qweqwe"
dici = {
"city": {
"coord": {
"lat": 123123123,
"lon": 123123
},
"country": "asdsd",
"id": 2735943,
"name": "qweqwe",
"population": 249633,
"sunrise": 1617689349,
"sunset": 1617735844,
"timezone": 3600
},
"cnt": 40,
"cod": "200",
"list": [
{
"clouds": {
"all": 0
},
"dt": 1617721200,
"dt_txt": "2021-04-06 15:00:00",
"main": {
"feels_like": 17.87,
"grnd_level": 1002,
"humidity": 65,
"pressure": 1014,
"sea_level": 1014,
"temp": 18.29,
"temp_kf": 0.25,
"temp_max": 18.29,
"temp_min": 18.04
},
"pop": 0,
"sys": {
"pod": "d"
},
"visibility": 10000,
"weather": [
{
"description": "clear sky",
"icon": "01d",
"id": 800,
"main": "Clear"
}
],
"wind": {
"deg": 299,
"speed": 3.36
}
},
{
"clouds": {
"all": 16
},
"dt": 1617732000,
"dt_txt": "2021-04-06 18:00:00",
"main": {
"feels_like": 15.78,
"grnd_level": 1001,
"humidity": 63,
"pressure": 1013,
"sea_level": 1013,
"temp": 16.44,
"temp_kf": 0.58,
"temp_max": 16.44,
"temp_min": 15.86
},
"pop": 0,
"sys": {
"pod": "d"
},
"visibility": 10000,
"weather": [
{
"description": "few clouds",
"icon": "02d",
"id": 801,
"main": "Clouds"
}
],
"wind": {
"deg": 295,
"speed": 2.21
}
}
]
}`
我想在temp_max大于16时提取数组列表的条目。我一直在做的是:
unwind = db.forecast.aggregate([
{"$unwind": "$list"},
{"$project":{"list.dt_txt":1,
"list.main.temp":1,
"list.main.temp_max":1,
"list.main.temp_min":1}},
{"$match":{"list.main.temp_max":{"$gt":10}}
}
])
a = db.forecast.aggregate([
{"$match":
{"list.main[*].temp_max": {"$gt": 10}}}
])
b = db.forecast.find({"list.main.temp_max":{"$gt":16}})
但是它们都有语法错误,我似乎找不到访问temp_max键的正确语法。有人能帮我吗?谢谢 您与第一个查询接近;这应该起作用:
unwind = db.forecast.aggregate([
{"$unwind": "$list"},
{"$match": {"list.main.temp_max": {"$gt": 16}}},
{"$project": {"list.dt_txt": 1, "list.main.temp": 1,
"list.main.temp_max": 1, "list.main.temp_min": 1, '_id': 0}}
])
或者,查找可以工作,但只匹配第一个列表项,因此聚合查询可能更好
b = db.forecast.find({"list.main.temp_max": {"$gt": 16}}, {'list.main.$': 1, '_id': 0})