In Mongoose, $elemMatch is an operator provided by MongoDB used to select elements in the array that match the specified query conditions when querying array fields. $elemMatch can apply multiple query conditions to the document objects within the array, and only elements that satisfy all conditions are selected.
For example, suppose we have a model called User that contains an awards array field, where each element is an object containing title and year. If we want to find users who won a specific award in a specific year, we can use $elemMatch to construct the query.
Here is a specific example:
javascriptconst mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ name: String, awards: [{ title: String, year: Number }] }); const User = mongoose.model('User', userSchema); // Query users who won the "Best Newcomer" award in 2020 User.find({ awards: { $elemMatch: { title: 'Best Newcomer', year: 2020 } } }) .then(users => { console.log(users); }) .catch(err => { console.error(err); });
In this query, we use $elemMatch to specify the search conditions for the awards array. Only when an element in the array satisfies both the title condition of 'Best Newcomer' and the year condition of 2020, the document containing this array is returned.
This is a basic example of using $elemMatch in Mongoose for querying, which is very suitable for cases where arrays contain multi-field objects and need to be filtered based on multiple conditions.