【问题标题】:how to query objects inside an object of a document from mongodb to retrieve matching key values based on the object's key如何从 mongodb 查询文档对象内的对象以根据对象的键检索匹配的键值
【发布时间】:2021-05-14 19:56:16
【问题描述】:

我在 Mongo 集合中有一个以下文档。

{
   "_id":"1001",
   "country":{
      "country_name":"India",
      "capital_city":"Delhi",
      "national_animal":"tiger",
      "national_bird":"peacock",
      
      "states":{
         "data":[
            {
               state_name : "karnataka",
               state_capital : "Bangalore"
            },
            {
               state_name : "maharashtra",
               state_capital : "Mumbai"
            },
            {
               state_name : "tamilnadu",
               state_capital : "Chennai"
            }
         ]
      }
   },
   "country_name":"India",
   "root_table":"country"
}

从这个 JSON 中,我只想要一个基于匹配过滤器 {"state_name" : "maharashtra"} 的对象的键值对。

要求的结果应该是这样的。

"states" : {
  state_name : "maharashtra",
  state_capital : "Mumbai"
}

{
  state_name : "maharashtra",
  state_capital : "Mumbai"
}

有没有可能实现这种类型的查询?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    尝试聚合查询,

    • $match 检查state_name 条件
    • $filter 迭代 data 数组的循环并检查是否找到 state_name
    • $arrayElemAt 从上述步骤的过滤结果中选择第一个元素
    • $project 显示必填字段
    db.collection.aggregate([
      { $match: { "country.states.data.state_name": "maharashtra" } },
      {
        $project: {
          state: {
            $arrayElemAt: [
              {
                $filter: {
                  input: "$country.states.data",
                  cond: { $eq: ["$$this.state_name", "maharashtra"] }
                }
              },
              0
            ]
          }
        }
      }
    ])
    

    Playground


    从 MongoDB 4.4 开始,您可以在 find() 方法中使用聚合 $project 阶段运算符,

    db.collection.find({
      "country.states.data.state_name": "maharashtra"
    },
    {
      state: {
        $arrayElemAt: [
          {
            $filter: {
              input: "$country.states.data",
              cond: { $eq: ["$$this.state_name", "maharashtra"] }
            }
          },
          0
        ]
      }
    })
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多