Open In App

Mongoose Query.prototype.elemMatch() API

Last Updated : 20 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose Query API.prototype.elemMatch() method of the Mongoose API is used on the Query objects. It allows us to match the documents that contains an array field, and along with that at least one element from that array list should match the query expression or filter condition. Let us understand elemMatch() method using an example.

Syntax:

query.elemMatch( path, filter );

Parameters: This method accepts two parameter as described below:

  • path: It is used to specify the path or field name from the collection.
  • filter: It is used to specify the filter condition. It can be object or a function.

Return Value: This method returns query object.

Setting up Node.js Mongoose Module:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this: 

 

Database Structure: The database structure will look like this, the following database present in the MongoDB.

 

Example 1: The below example illustrates the basic functionality of the Mongoose Connection elemMatch() method. We are fetching all the documents where any of the element in marks array is greater than 80.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const studentSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: Number,
    rollNumber: { type: Number, required: true },
    marks: []
});
  
const StudentModel = connectionObject.model('Student', studentSchema);
  
const query = StudentModel.find()
query.where('marks');
query.elemMatch({ $gte: 80 })
query.exec((error, result) => {
    if (error) {
        console.log("Error -", error);
    } else {
        console.log("Result -", result);
    }
})


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

Result - [
  {
    _id: new ObjectId("63c2f65ae00fb130bfb5075b"),
    name: 'Student2',
    age: 18,
    rollNumber: 65,
    marks: [ 52, 36, 45, 85, 21 ],
    __v: 0
  },
  {
    _id: new ObjectId("63c2f65ae00fb130bfb5075c"),
    name: 'Student3',
    age: 15,
    rollNumber: 36,
    marks: [ 85, 69, 42, 32, 16 ],
    __v: 0
  }
]

Example 2: The below example illustrates the basic functionality of the Mongoose Connection elemMatch() method. We are fetching all the documents where any of the element in marks array is greater than 20 and less than 50.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const studentSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: Number,
    rollNumber: { type: Number, required: true },
    marks: []
});
  
const StudentModel = connectionObject.model('Student', studentSchema);
  
const query = StudentModel.find()
query.elemMatch('marks', { $gte: 20, $lte: 50 })
query.then(res => {
    console.log(res);
}).catch(err => console.log(err));


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

[
  {
    _id: new ObjectId("63c2f65ae00fb130bfb5075a"),
    name: 'Student1',
    age: 25,
    rollNumber: 36,
    marks: [ 25, 35, 61, 28, 45 ],
    __v: 0
  },
  {
    _id: new ObjectId("63c2f65ae00fb130bfb5075b"),
    name: 'Student2',
    age: 18,
    rollNumber: 65,
    marks: [ 52, 36, 45, 85, 21 ],
    __v: 0
  },
  {
    _id: new ObjectId("63c2f65ae00fb130bfb5075c"),
    name: 'Student3',
    age: 15,
    rollNumber: 36,
    marks: [ 85, 69, 42, 32, 16 ],
    __v: 0
  }
]

Reference: https://mongoosejs.com/docs/api/query.html#query_Query-elemMatch



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads