Search code examples
mongodbmongodb-queryaggregation-frameworkphp-mongodb

How to check empty array in if condition in mongodb query?


I am trying to find whether the array is empty or not by writing following mongodb projection query with if else condition.

                [
                  '$project' => [ 
                      '_id' => 1.0,
                      'Name' => 1.0,
                       'AllotmentsDetails' => 1.0,
                       'NonExpiredAllotmentsOfRoomWithCheckoutZero' => 1.0,
                       'NonExpiredAllotmentsOfRoomWithCheckoutOne' => 1.0,
                       'NonExpiredAllotmentsOfRoom' => 1.0,      
                       'RecentAllotmentsDetails' =>  [
                            '$cond'=> [
                              'if'=> [
                                '$not' => ['$NonExpiredAllotmentsOfRoom' => [ '$size' => 0 ]]
                               ],
                               'then' => ['$arrayElemAt' => ['$NonExpiredAllotmentsOfRoom', -1 ]],
                               'else' => []
                              ]
                        ]    
                ]]    

Basically I am trying to check whether '$NonExpiredAllotmentsOfRoom' is empty or not. if it is empty it should return empty array otherwise it should return last element of '$NonExpiredAllotmentsOfRoom'. The above code is throwing error message "Unrecognized expression '$NonExpiredAllotmentsOfRoom". Please help !!!


Solution

  • RecentAllotmentsDetails =>  {
                                  $cond: { if: { $ne: [ 
                                  "$NonExpiredAllotmentsOfRoom", [] ] }, 
                                   then: ['$arrayElemAt' => 
                                          ['$NonExpiredAllotmentsOfRoom', -1 ]] ,
                                   else: []
                                    }   
    
                                  }
    

    try this in your pipeline