$filter upto 2 nested level in mongodb

前端 未结 1 1749
萌比男神i
萌比男神i 2021-01-25 05:20

i have a database structured like this:

1条回答
  •  情歌与酒
    2021-01-25 06:13

    You need to $unwind the first array then you can easily apply $filter on the nested array

    db.collection.aggregate([
      { "$unwind": "$Hospitais" },
      { "$match": { "Hospitais.nome": "Dorio Silva" } },
      { "$project": {
        "Hospitais": {
          "$filter": {
            "input": "$Hospitais.utis",
            "as": "uti",
            "cond": {
              "$eq": ["$$uti.nome", "UTI1"]
            }
          }
        }
      }}
    ])
    

    Or you can try this as well

    db.collection.aggregate([
      { "$match": { "Hospitais.nome": "Dorio Silva" } },
      { "$project": {
        "Hospitais": {
          "$filter": {
            "input": {
              "$map": {
                "input": "$Hospitais",
                "as": "hospital",
                "in": {
                  "nome": "$$hospital.nome",
                  "utis": {
                    "$filter": {
                      "input": "$$hospital.utis",
                      "as": "uti",
                      "cond": {
                        "$eq": ["$$uti.nome", "UTI1"]
                      }
                    }
                  }
                }
              }
            },
            "as": "hospital",
            "cond": {
              "$eq": ["$$hospital.nome", "Dorio Silva"]
            }
          }
        }
      }}
    ])
    

    Both will give the similar output

    [
      {
        "Hospitais": [
          {
            "_id": 893910,
            "leitos": [
              {
                "_id": 1.2893812e+08,
                "_paciente": "Oliver"
              },
              {
                "_id": 1.2803918239e+10,
                "_paciente": "Priscilla"
              }
            ],
            "nome": "UTI1"
          }
        ]
      }
    ]
    

    0 讨论(0)
提交回复
热议问题