Home > Enterprise >  Query for "is not null" not working in MongoDB
Query for "is not null" not working in MongoDB

Time:04-11

Im working with a mongodb table and I have problems to get the documents with values different from null in some field. I asume that im using the $ne operator wrong, but, given this document:

{
  "createdAt" : "2022-04-07T13:18:18Z",
  "expired" : false,
  "responses": [
    {
      "id": "header",
      "options": [
        {
          "id": "1",
          "text": ""
        }
      ],
      "textForSearch": null
    },
    {
      "id": "content",
      "options": [
        {
          "id": "content test 01",
          "text": "content test 01"
        },
        {
          "id": "content test 02",
          "text": "content test 02"
        }
      ],
      "title": "test title",
      "questionType": "selection",
      "textForSearch": null
    },
    {
      "id": "footer",
      "options": [
        {
          "id": "negative",
          "text": "Negative"
        },
        {
          "id": "positive",
          "text": "Positive"
        }
      ],
      "title": "test title",
      "questionType": "selection",
      "textForSearch": null
    },
    {
      "id": "test_id",
      "options": null,
      "title": "",
      "questionType": "text",
      "textForSearch": "comentario de test"
    }
  ]
}

The following query:

db.getCollection('table').find({"responses.textForSearch": {$ne: null} })

result in:

Fetched 0 record(s) in 1ms.

What am I missing?

CodePudding user response:

Use $elemMatch operator.

You may refer to Single Query Condition to see the sample that using dot notation and $elemMatch produce the different results when using with $not or $ne operators.

db.collection.find({
  "responses": {
    "$elemMatch": {
      "textForSearch": {
        $ne: null
      }
    }
  }
})

Sample Mongo Playground

  • Related