'Query with $elemMatch returns unexpected results

I have the following documents:

  {
    _id: ObjectId("6266d9ad44d8051197ac7507"),
    aircraftCode: '1b7ad0de-5836-489b-9791-5a81a51cdb81',
    crew: [
      {
        name: 'Nina Peltier',
        position: 'Attendant',
        nationality: 'France',
        hoursSlept: 6
      },
      {
        name: 'Lou Galopin',
        position: 'Attendant',
        nationality: 'France',
        hoursSlept: 7
      }
    ]
  },
  {
    _id: ObjectId("6266d9ad44d8051197ac7508"),
    crew: [ { name: 'Popescu Ion', position: 'Captain', hoursSlept: 8 } ]
  },
  {
    _id: ObjectId("6266d9ad44d8051197ac7509"),
    aircraftCode: 'eede6be6-f716-4e2e-bf81-885f0a16a50c',
    crew: [
      {
        name: 'Pierre Cotard',
        position: 'Captain',
        nationality: 'France',
        hoursSlept: 4
      },
      { name: 'Amanda Lucas', position: 'Attendant', hoursSlept: 6 },
      {
        name: 'Joe Stan',
        position: 'Attendant',
        nationality: 'UK',
        hoursSlept: 8
      }
    ]
  }

I want to find only those where 'Captain' is not in the crew.

This works:

db.flights.find({ "crew.position": { $ne: "Captain" }  })

This doesn't work:

db.flights.find({ crew: { $elemMatch: { position: { $ne: "Captain" } } } })

It returns also documents where the captain is present.

What's wrong with my second query?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source