0

I'm working with a MongoDB table and I have problems getting the documents with values different from null in some fields. I assume that I'm 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?

1 Answer 1

2

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

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

1 Comment

Im testing this and seems to work fine. I didnt know about $elemMatch, Im pretty new at mongodb. Thank you very much for your time and contribution.

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.