Home > Mobile >  How to check if a field is null in array of documents
How to check if a field is null in array of documents

Time:11-03

{
    school:[
        {
            student:"raj",
            subjects:["P","C","M"],
            std:10
        },
        {
            student:"ram",
            subjects:[],
            std:8
        },
        {
            student:"rahul",
            subjects:["P"],
            std:9
        }
    ]
}

I want this output without 'std' and don't want subjects array if it is null please help

{
    school:[
        {
            student:"raj",
            subjects:["P","C","M"]
        },
        {
            student:"ram",
        },
        {
            student:"rahul",
            subjects:["P"]
        }
    ]
}

Please help I think map would be used but am not able to form the mongodb query

CodePudding user response:

If you just wanted to remove a field, like for example the std field your could have just used a simple query with the projection options, like so:

db.collection.find({},
{
  "schoo.std": 0
})

Mongo Playground

However because you want to do a "conditional projection", i.e only show a field if it's not "null" (or empty array as your sample shows) this will require you to use the aggregation framework as it will require some stronger structure manipulation, here's how I'd do it using the $map operator:

db.collection.aggregate([
  {
    $project: {
      school: {
        $map: {
          input: "$school",
          in: {
            student: "$$this.student",
            subjects: {
              $cond: [
                {
                  $eq: [
                    0,
                    {
                      $size: {
                        $ifNull: [
                          "$$this.subjects",
                          []
                        ]
                      }
                    }
                  ]
                },
                "$$REMOVE",
                "$$this.subjects"
              ]
            }
          }
        }
      }
    }
  }
])

Mongo Playground

  • Related