Mankind1023
Mankind1023

Reputation: 7732

mongodb $cond if array is not empty

I'm trying to add a push with a conditional "if myArray.length > 0" basically:

$push: {
    $cond: [
            { // how check if myArray.length > 0 here? },
            1, // this value is just for testing
            "$$REMOVE"
    ]
}

So far none of the combinations I have tried or online answers have worked, so I have no idea what I'm doing wrong here.

Upvotes: 0

Views: 2686

Answers (1)

Joe
Joe

Reputation: 28336

Since you can't check the length of myArray if it is missing or otherwise not an array, you need a nested $cond.

The outer one tests if the type of myarray to make sure it is an array, the inner one checks the length of the array.

        $cond: {
          if: {$eq: [ "array", {$type: "$myArray" }]},
          then: {
           $cond: {
              if: {$gt: [{ $size: "$MYARRAY"}, 0]},
              then: 1,
              else: "$$REMOVE"
           }},
          else: "$$REMOVE"
        }

playground

Upvotes: 1

Related Questions