$elemMatch

noun

say it: “DOL-er EL-em MACH” /ˈdɑlər ˈɛləm ˈmætʃ/

A MongoDB filter operator that matches an array only when one of its items meets all the given conditions together.

What does $elemMatch do in a MongoDB filter?

$elemMatch matches an array of documents only when one single item meets every condition you list. Without it, each condition may be met by a different item.

db.recipes.find(
  { ingredients: { $elemMatch: { item: "flour", grams: { $gte: 500 } } } },
  { _id: 0, name: 1 }
);
// [ { name: 'Sourdough Loaf' } ]

In a sentence

  • “$elemMatch keeps both conditions on the same ingredient.”
  • “With $elemMatch, the search found recipes using at least 500 grams of flour, not 500 grams of something else.”

Level: Journeyman · More MongoDB terms at this level

Updated