Piero.Sgri
Piero.Sgri

Reputation: 43

Return document where all elements of nested array match

I'm trying to write a query that return all documents where descrtratt: "Chemioterapia" and nomemed: "null".

This is what I tried:

db.pazienti.find({terapie: {$elemMatch: {descrtratt: "Chemioterapia", nomemed: "null"}}})

The query I wrote, however, returns documents where at least one element of the terapie array match, what I want is return all documents where ALL the elements of the terapie array match.

Considering these 4 inputs documents below, the returned documents should be only the 2nd and the 4th one. My query returns all 4 documents instead, how should I fix it?

{
"codf": "001", 
"nome": "Michelangelo", 
"cognome": "Milani", 
"terapie": [
    {
        "descrtratt": "Chemioterapia", 
        "nomemed": "null", 
    }, 
    {
        "descrtratt": "Chemioterapia",  
        "nomemed": "Busulfano",  
    }
    ]
}
{
"codf": "004", 
"nome": "Gigio", 
"cognome": "Battisti", 
"terapie": [
    {
        "descrtratt": "Chemioterapia", 
        "nomemed": "null", 
    }, 
    {
        "descrtratt": "Chemioterapia",  
        "nomemed": "null",  
    }
    ]
}
{
"codf": "007", 
"nome": "Giovanni", 
"cognome": "Bomba", 
"terapie": [
    {
        "descrtratt": "Chemioterapia", 
        "nomemed": "null", 
    }, 
    {
        "descrtratt": "Radioterapia",  
        "nomemed": "null",  
    }
    ]
}
{
"codf": "023", 
"nome": "Luca", 
"cognome": "Agostinelli", 
"terapie": [
    {
        "descrtratt": "Chemioterapia",  
        "nomemed": "null",  
    }
    ]
}

Upvotes: 1

Views: 355

Answers (1)

turivishal
turivishal

Reputation: 36094

You can use negative condition $ne inside $elemMatch with $nor operator,

db.pazienti.find({
  $nor: [
    {
      terapie: {
        $elemMatch: {
          descrtratt: { $ne: "Chemioterapia" }
        }
      }
    },
    {
      terapie: {
        $elemMatch: {
          nomemed: { $ne: "null" }
        }
      }
    }
  ]
})

Playground

Upvotes: 1

Related Questions