【问题标题】:Need help to query nested array on mongo在 mongodb 上查询嵌套数组需要帮助
【发布时间】:2021-08-02 18:03:53
【问题描述】:

我在 mongo db 中有以下文档结构

{
"_id": {
    "name": "XYX",
    "rol_no": "1",
    "last_update_dt": "2021-05-10",
    
},
"stud_history": [{
    'std': 'xyz',
    'age': '16'
},
{
    'std': 'mnl',
    'age': '15'
}]
}

我想查询类似的数据

name:xyz, rol_no:1, last_update_dt: 2021-05-10 and age:16

这里我只提到了 1 个学生,但我需要类似地查询多个学生。

所以我的输出将是

"_id": {
    "name": "XYX",
    "rol_no": "1",
    "last_update_dt": "2021-05-10",

},
'stud_history': {
    'std': 'xyz',
    'age': '16'
}

请帮忙

【问题讨论】:

    标签: mongodb sub-array


    【解决方案1】:

    您必须在 match 命令的投影参数中使用 $elemMatch 运算符来过滤匹配特定条件的输出。

    db.collection.find({  // Find Query
      "_id.name": "XYX",
      "_id.rol_no": "1",
      "_id.last_update_dt": "2021-05-10",
    },
    {  // Projection Parameter
      "_id": 1,
      "stud_history": {
        "$elemMatch": {  // Filters array elements to those matching the provided condition
          "age": "16"
        }
      }
    })
    

    如果您想使用聚合实现相同的目的,请使用以下查询:

    db.collection.aggregate([
      {
        "$match": {
          "_id.name": "XYX",
          "_id.rol_no": "1",
          "_id.last_update_dt": "2021-05-10",
          
        }
      },
      {
        "$project": {
          "_id": 1,
          "stud_history": {
            $filter: {
              input: "$stud_history",
              as: "item",
              cond: {
                $eq: [ "$$item.age", "16" ]
              }
            }
          }
        }
      },
      {
        // If you want the result to be an object instead of an array
        "$unwind": "$stud_history"
      },
    ])
    

    【讨论】:

    • 你能发布聚合吗?
    • 在答案中添加聚合示例
    猜你喜欢
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    相关资源
    最近更新 更多