", -6ren">
gpt4 book ai didi

采用 json 对象的 Python 函数返回 mongodb 查询对象

转载 作者:行者123 更新时间:2023-12-04 15:03:17 24 4
gpt4 key购买 nike

我需要取一个JSON(过滤数据的条件),示例数据:

query = { "and": [
{
"field": "model",
"operator": ">",
"value": "2005"
},
{
"or": [
{
"field": "brand",
"operator": "=",
"value": "Mercedes"
},
{
"field": "brand",
"operator": "=",
"value": "BMW"
}
]
}
]

并编写一个将此 JSON 转换为 MongoDB 查询的函数,这样我就可以在从 MongoDb 读取数据时直接过滤数据(我将在 apache beam ReadFromMongoDB 函数中使用此数据,作为过滤对象)

所以输出应该是这样的:

{'$and': [{'field': 'model', 'operator': '>', 'value': '2005'}, {
'$or': [
{'field': 'brand', 'operator': '=', 'value': 'Mercedes'},
{'field': 'brand', 'operator': '=', 'value': 'BMW'}
]
}]}

(我有一个函数可以将每个单个对象转换为 MongoDB 查询,所以不用担心)

我尝试了什么

因为我不知道嵌套数据是怎么来的,所以我在我的函数中使用了递归。但是它变得复杂并且输出不像我预期的那样。

def splitToItems(query, items={}):
if 'and' in query:
for item in query['and']:
if 'and' in item or 'or' in item:
splitToItems(item)
else:
if '$and' not in items:
items['$and'] = [item]
# print(items)
else:
items['$and'].append(item)
# print(items)


if 'or' in query:
for item in query['or']:
if 'and' in item or 'or' in item:
return splitToItems(item)
else:
if '$or' not in items:
items['$or'] = [item]
# print(items)
else:
items['$or'].append(item)
# print(items)
print(items)

-------
OUTPUT:

# '$or' should have been inside of the first array in this case

{
'$and': [{'field': 'model', 'operator': '>', 'value': '2005'}],
'$or': [{'field': 'brand', 'operator': '=', 'value': 'Mercedes'}, {'field': 'brand', 'operator': '=', 'value': 'BMW'}]
}

关于如何改进此功能或使其发挥作用有什么想法吗?非常感谢

最佳答案

希望我能正确理解问题

def splitToItems(query, items={}):
q = {}
if 'and' in query:
l = []
for item in query['and']:
l.append(splitToItems(item))
q["$and"] = l

if 'or' in query:
l = []
for item in query['or']:
l.append(splitToItems(item))
q["$or"] = l

if q:
return q
return query

print(splitToItems(query))

这是否解决了您的问题?

关于采用 json 对象的 Python 函数返回 mongodb 查询对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66589054/

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