【问题标题】:Python function that takes a json object returns mongodb query object接受 json 对象的 Python 函数返回 mongodb 查询对象
【发布时间】:2021-06-09 19:56:23
【问题描述】:

我需要取一个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'}]
}

关于如何改进此功能或使其工作的任何想法?非常感谢提前

【问题讨论】:

    标签: python json python-3.x django mongodb


    【解决方案1】:

    希望我能正确理解这个问题

    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))
    

    这能解决您的问题吗?

    【讨论】:

    • 是的!非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多