1

This is example one of document in MongoDB.

{
    "content" : "I just said that before. I'll never be with you.",
    "analysis" : [
        {
            "sentence" : "I just said that before.",
            "sentiment" : "neutral",
            "subject" : "I",
            "expression" : "say"
        },
        {
            "sentence" : "I'll never be with you.",
            "sentiment" : "negative",
            "subject" : "I",
            "expression" : "be",
            "label": "Farewell"
        }
    ]
}

There every analysis element can has "label" or no.

I want to filter this document for put "label" in analysis element.

I need document list that analysis.label.count < analysis.count

I tried this query
{ $and: [{ "analysis": { $exists: true } }, { "analysis.label": { $exists: false } }] }.

But it returns only has no label in any analysis' element.

Do I need aggregate()? or find() with query?

2
  • 1
    simply check condition .find({ "analysis.label": null }). Commented Nov 5, 2021 at 8:27
  • @turivishal chaged query { $and: [{ "analysis": { $exists: true } }, { "analysis.label": null }] } It work! I don't know how 'null' works. Commented Nov 5, 2021 at 8:33

1 Answer 1

1

It requires $elemMatch operator to match $exists false condition in array,

{
  analysis: {
    $exists: true,
    $elemMatch: {
      label: {
        $exists: false
      }
    }
  }
}

Playground


The second approach checking null condition,

{
  analysis: {
    $exists: true
  },
  "analysis.label": null
}

Playground

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

2 Comments

Oh, It work. Is there difference with your condition and this { $and: [{ "analysis": { $exists: true } }, { "analysis.label": null }] }? Both query returns same result.
the $exists will check if the property exists in the document, and the null will check both the conditions, if the field exists or if it exists then null? so both will work in your situation.

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.