Skip to content
Related Articles

Related Articles

Improve Article

How does Query.prototype.elemMatch() work in Mongoose ?

  • Last Updated : 17 Mar, 2021

The Query.prototype.elemMatch() function is used to specify the $elemMatch condition. It matches the documents that contain an array field with at least single or one element that will matches all the specified query criteria.

Syntax:

Query.prototype.elemMatch()

Parameters: This function has two parameters, ie. path and filter.

Return Value: This function returns Query Object.
Installing mongoose.;

npm install mongoose

After installing the mongoose module, you can check your mongoose version in command prompt using the command.



npm mongoose --version

Now, create a folder and add a file, for example, index.js as shown below.

Database: The sample database used here is shown below: 
 

Project Structure: The project structure will look like this.

Example 1:

index.js




const mongoose = require('mongoose');
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
var query = User.find({});
query.where('user').elemMatch(function (elem) {
      
    if (elem) {
        console.log("Element Present")
    }
      
    elem.where('age').gte(100);
  
}).exec(function(err, res){
    if(err) console.log(err)
    console.log(res)
})

Run index.js file using below command:

node index.js

Output: 

Element Present
[]    // No age is greater than 100

Example 2:

index.js




const express = require('express');
const mongoose = require('mongoose');
const app = express()
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
var query = User.find({});
  
query.where('user').elemMatch(function (elem) {
      
    if (elem) {
        console.log("Element Present")
    }
      
    elem.where('age').gte(155);
  
}).exec(function(err, res){
    if(err) console.log(err)
    console.log(res)
})
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});

Run index.js file using below command: 
 

node index.js

Output: 

Server listening on PORT 3000
Element Present
[]    // No age is greater than 155

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :