【问题标题】:Mongodb: Query documents that matches unknown keyMongodb:查询匹配未知键的文档
【发布时间】:2020-05-19 01:00:10
【问题描述】:

我有一个包含以下结构的文档的集合:

{
  "userId": "57e32f05-fca1-452c-aace-76f35962fe4a",
  "availableSearches": {
    "7fcb6d67-f825-41ca-b47c-fecaedc738c7": {
      "searchType": "RECENT",
      "searchId": "7fcb6d67-f825-41ca-b47c-fecaedc738c7",
      "enabled": false,
    }
    "2b59ee7b-256b-47c2-9573-18676951cb0d": {
      "searchType": "RECENT",
      "searchId": "2b59ee7b-256b-47c2-9573-18676951cb0d",
      "enabled": true,
    }
  }
}

我有一个 id 列表:

["7fcb6d67-f825-41ca-b47c-fecaedc738c7", 
 "2b59ee7b-256b-47c2-9573-18676951cb0d",
 ...]

availableSearches 对象的键未知。

我想在 1 个查询中获取所有文档,即 availableSearches.${KEY} 存在或 availableSearches.${KEY}.searchId 等于 ${KEY}。即与列表中的键匹配的文档。

有没有办法在mongodb中做到这一点?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你可以试试下面aggregation查询:

    db.collection.aggregate([
       /** Add a new field to all docs where `availableSearches` will converted to an array of [{k:...,v:...},{k:...,v:...}]*/
      {
        $addFields: { availableSearchesConverted: { $objectToArray: "$availableSearches" } }
      },
      /** Match on k field of new array */
      {
        $match: {
          "availableSearchesConverted.k": {
            $all: [ // Use `$in` if you wanted to get docs if atleast one value exists. `$all` checks for all input elements should exists
              "7fcb6d67-f825-41ca-b47c-fecaedc738c7", "2b59ee7b-256b-47c2-9573-18676951cb0d"
            ]
          }
        }
      },
      /** Remove newly created field from output */
      {
        $project: {
          availableSearchesConverted: 0
        }
      }
    ])
    

    测试: mongoplayground

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 2019-05-06
      • 2020-11-17
      • 1970-01-01
      • 2018-08-20
      • 2015-03-12
      • 2021-08-07
      • 1970-01-01
      • 2017-02-19
      相关资源
      最近更新 更多