Home > Blockchain >  How to filtering list with count sub array's field?
How to filtering list with count sub array's field?

Time:11-05

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?

CodePudding user response:

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

  • Related