Skip to content

Instantly share code, notes, and snippets.

@alkaaf
Created July 18, 2023 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alkaaf/4091ffbe3b7dff5ec45a395e45b68e0f to your computer and use it in GitHub Desktop.
Save alkaaf/4091ffbe3b7dff5ec45a395e45b68e0f to your computer and use it in GitHub Desktop.

i want to filter which data have empty size of "pembayaran_umum". in atlas there are no specific operator to check whether an array is empty or not.

this is the data looks like

[
  {
    "idtransaksi": "JUT201117085946197",
    "customer_idcustomer": "CFELE15914130508DI",
    "pembayaran_umum": [
      {
        "idtransaksi": "JUT201117085946197",
        "bayar": 4500
      }
    ]
  },
  {
    "idtransaksi": "IEO230623104801831",
    "customer_idcustomer": "LCEOA1673578290YYF",
    "pembayaran_umum": []
  },
  {
    "idtransaksi": "IEO230623104801831",
    "customer_idcustomer": "LCEOA1673578290YYF",
    "pembayaran_umum": []
  }
]

in mongodb, i can do this easily with this query

{
  "pembayaran_umum": []
}

or

{
  "pembayaran_umum": {
    "$size": 0
  }
}

but in atlas, i cant get the array size to check or even put []. Exists also no use because it is there but empty. so instead of checking the "pembayaran_umum" field like this

[
  {
    "$search": {
      "index": "main_full_1",
      "compound": {
        "mustNot": {
          "exists": {
            "path": "pembayaran_umum"
          }
        }
      }
    }
  }
]

i put "guaranteed non null field" inside "pembayaran_umum" as path. it will check the field exists or not. if the array is empty, the path wouldn't exist. but if the array is not empty, the path will be there

[
  {
    "$search": {
      "index": "main_full_1",
      "compound": {
        "mustNot": {
          "exists": {
            "path": "pembayaran_umum.idtransaksi"
          }
        }
      }
    }
  }
]

if i want to check the array is not empty, i just change the must with mustNot

[
  {
    "$search": {
      "index": "main_full_1",
      "compound": {
        "must": {
          "exists": {
            "path": "pembayaran_umum.idtransaksi"
          }
        }
      }
    }
  }
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment