Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

The Query.prototype.lt() function is used to specify a $lt query condition. It returns documents that are less than the specified condition.
 

Syntax: 

Query.prototype.lt()

Parameters: This function has val parameter and an optional path parameter.
Return Value: This function returns Query Object.

Mongoose Installation:

npm install mongoose

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

npm mongoose --version

After that, you can just create a folder and add a file for example, index.js as shown below.

Database: The sample database used here is shown below: 
 

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('age').lt(10).exec(function(err, res){
    if(err) console.log(err.message)
    else console.log(res)
});


The project structure will look like this: 
 

Run index.js file using below command: 

node index.js

Output: 

[ { _id: 5ebc367da99bde77b2efb9bf, name: ‘Piyush’, age: 5, __v: 0 } ]

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('age').lt(25).exec(function(err, res){
    if(err) console.log(err.message)
    else console.log(res)
});
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});


The project structure will look like this: 
 

Run index.js file using below command: 

node index.js

Output: 

Server listening on PORT 3000
[
{ _id: 5ebb9129a99bde77b2efb809, name: ‘Gourav’, age: 10, __v: 0 },
{ _id: 5ebc367da99bde77b2efb9bf, name: ‘Piyush’, age: 5, __v: 0 }
]

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



Last Updated : 17 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads