【问题标题】:MongoDb : Find and filter values from nested mapMongoDb:从嵌套地图中查找和过滤值
【发布时间】:2021-12-27 00:22:43
【问题描述】:

我在 mongo db 中有一些约会

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "orgId": "606abce197dc265ac41ae82c",
    "registrations": {
      "id1": {
        "status": "status",
        "topStage": {
          "id": "stage1",
          "name": "stage1"
        }
      },
      "id2": {
        "status": "status",
        "topStage": {
          "id": "stage1",
          "name": "stage1"
        }
      },
      "id3": {
        "status": "status",
        "topStage": {
          "id": "stage2",
          "name": "stage2"
        }
      }
    }
  }
]

我希望传递一个阶段 id(在路径注册-> topStage -> id 处)并返回所有匹配的键值。

我写了以下查询

db.collection.aggregate([
  {
    $project: {
      teams: {
        $objectToArray: "$registrations"
      },
      original: "$$ROOT"
    }
  },
  {
    "$project": {
      "teams": {
        "$filter": {
          "input": "$teams",
          "as": "team",
          "cond": {
            "$eq": [
              "$$team.v.topStage.id",
              "stage1"
            ]
          }
        }
      }
    }
  },
  {
    "$project": {
      "registrations": {
        "$arrayToObject": "$teams"
      }
    }
  }
])

它确实返回了正确的值 为 stage1 作为阶段 id

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "registrations": {
      "id1": {
        "status": "status",
        "topStage": {
          "id": "stage1",
          "name": "stage1"
        }
      },
      "id2": {
        "status": "status",
        "topStage": {
          "id": "stage1",
          "name": "stage1"
        }
      }
    }
  }
]

对于stage2作为stage id,它返回

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "registrations": {
      "id3": {
        "status": "status",
        "topStage": {
          "id": "stage2",
          "name": "stage2"
        }
      }
    }
  }
]

有人可以告诉我这是编写此查询的最佳方式还是可以简化??

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    这是正确的做法,但在以下情况下会影响性能。

    • 如果您没有针对索引的任何其他匹配条件
    • 如果您有一个匹配条件并且它匹配少数文档,其中注册具有更多对象

    您可以做的其他最佳选择是更改架构。

    • 您可以将registrations.id1 保留为registrations : { id:1, status_id: 2}
    • 或者您可以更改方式,使其不需要在更大的集合上使用 objectToArray
    • 如果您的数据量很大,我建议在嵌套状态 Id 字段上添加索引。

    mongo 文档本身建议评估任何数据的多个模式以充分利用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 2020-08-19
      相关资源
      最近更新 更多