需要帮助在 mongo 上查询嵌套数组

问题描述

我在 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",'stud_history': {
    'std': 'xyz','age': '16'
}

请帮忙

解决方法

您必须在 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",}
  },{
    "$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"
  },])