Search code examples
mongodbmongoosemongodb-query

Or with If and In mongodb


{
  $cond: {
    if: { $in: [`$$${field.fieldName}`, ['', null]] },
    then: [],
    else: `$$${field.fieldName}`,
  },
},

In this condition, I also want to check the field.fieldName exits.

$exists: true,

then it will something like

if ( !filed.fieldName || field.fieldName === null || field.fieldName === '') then []

I am not finding any way to add $exits: true or false in this. Please help if can add something to this. Or any alternate way to achieve ?


Solution

  • You just need to put $ifNull in else part, if it's not exists it will return [],

    {
      $cond: {
        if: {
          $in: [`$$${field.fieldName}`, ["", null]]
        },
        then: [],
        else: { $ifNull: [`$$${field.fieldName}`, []] }
      }
    }
    

    Playground

    Input:

    [
      { "key": null },
      { "key": "" },
      { "A": "a" }
    ]
    

    Result:

    [
      {
        "key": null,
        "status": []
      },
      {
        "key": "",
        "status": []
      },
      {
        "status": []
      }
    ]
    

    Second approach, if you want to add an existing condition in if part you can try condition with $or,

    • $type will return the field's data type the missing field type is "missing"
    {
      $cond: {
        if: {
          $or: [
            { $eq: [{ $type: `$$${field.fieldName}` }, "missing"] },
            { $in: [`$$${field.fieldName}`, ["", null]] }
          ]
        },
        then: [],
        else: `$$${field.fieldName}`
      }
    }
    

    Playground