首页 > 解决方案 > mongodb查询具有未知属性的第三级

问题描述

我需要在 mongodb 中执行查询。文件存储如下

    {
        "_id": "5b506440a7769100817265b2",
        "zones": [
            "London",
            "Berlin",
            "Rome"
        ],
        "width": 100,
        "price_list_id": 2,
        "heights": {
            "200": {
                "window_fixed_arch_low": {
                    "default": false,
                    "price": "2"
                }
            },
            "300":{
                "window_fixed_arch_regular": {
                    "default": false,
                    "price": "3"
                }
            }
        }
    }

我只想检索所有具有heights.*.window_fixed_arch_regular属性的文档。我试过了

({'heights.$.window_fixed_arch_regular', 'exists', true})

但没有运气。

在所有高度(在我的情况下为 200 和 300)中“搜索”而不指定它并检查“window_fixed_arch_low”是否存在的查询是什么?

标签: mongodbmongodb-queryaggregation-framework

解决方案


您可以在 3.6 中使用以下查询。

$objectToArrayheights文档转换为键值对,然后$filter将输入值与文档中的值进行比较。

$expr在查找查询中接受聚合表达式。

$gt > null- 聚合表达式检查匹配值存在的位置,然后$size输出计数。

$gt > 0- 聚合表达式检查计数大于 0 的位置。

db.collectionName.find({
  "$expr":{
    "$gt":[
      {"$size":{
        "$filter":{
          "input":{"$objectToArray":"$heights"},
          "cond":{"$gt":["$$this.v.window_fixed_arch_low",null]}
        }
      }},
      0
    ]
  }
})

推荐阅读