VOOZH about

URL: https://www.geeksforgeeks.org/mongodb/mongoose-query-api-2/

⇱ Mongoose Query() API - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mongoose Query() API

Last Updated : 28 Apr, 2025

The Mongoose API Query() method of the Mongoose API is used as a constructor to create a reference of Query. It allows us to create query objects and build query expressions. We do not need to create an object of the Query class in order to interact with the MongoDB collection. We can directly call any model method on custom defined Model which will indirectly return the instance of Query. Let us understand the Query() constructor using an example.

Syntax:

new mongoose.Query( options, model, conditions, collection );

Parameters: This method accepts four parameters as described below:

  • options: It is used to specify various properties for the constructor.
  • model: It is used to specify the model name.
  • conditions: It is used to specify the filter conditions.
  • collection: It is used to specify the name of the collection in the database.

Return Value: This constructor returns a reference of the Query class.

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: 

👁 Image
 

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

👁 Image
 

Example 1: The below example illustrates the basic functionality of the Mongoose Connection Query() constructor. We can see that the query object is the instance of the Query class, which is indirectly instantiated while using find() on the mongoose model.

Filename: app.js

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

node app.js

Output:

true

Example 2: The below example illustrates the basic functionality of the Mongoose Connection Query() constructor. At the end, we are using a query object which is the instance of the Query constructor in order to get the documents from the collection.

Filename: app.js

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("63c2fe2ef9e908eb17f225db"),
 name: 'Student2',
 age: 18,
 rollNumber: 65,
 __v: 0
 }
]

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

Comment

Explore