0

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 !!!

1
  • Can you post a few sample data? Commented Nov 15, 2019 at 8:51

1 Answer 1

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

                              }

try this in your pipeline

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.