Mongoose queries let MongoDB find, add, update, or delete data, from simple lookups to advanced filtering, sorting, and counting, in an easy and organized way.
Commonly used to:
- Retrieve documents from MongoDB (Read).
- Add new documents (Create).
- Modify existing documents (Update).
- Remove documents (Delete).
Syntax:
const Student = mongoose.model('Student', studentSchema);
Student.findOneAndUpdate({ name: 'John' },
function (err, student) {
if (err) return handleError(err);
else{
// Updated successfully
}
});
In the above syntax:
- mongoose.model('Student', studentSchema): Creates the Student model.
- findOneAndUpdate({ name: 'John' }, …): Finds a student named John and updates it.
- Callback (err, student): Handles errors or confirms successful update.
Different Types of Mongoose Queries
Mongoose offers a variety of queries to interact with your MongoDB database. These queries allow us to perform CRUD (Create, Read, Update, Delete) operations efficiently. Below are the most commonly used Mongoose queries:
1. Model.deleteMany(): This query takes the parameters of any field that matches and then deletes all the entries in the database that matches.
Student.deleteMany({ age: { $gt: 18 } });2. Model.deleteOne(): This query takes the parameters of any field that matches and then deletes any one of the entries in the database that matches.
Student.deleteOne({ name: 'John' });3. Model.find(): This query takes the parameters of one or more fields that match and then returns all the entries in the database that matches.
Student.find({ age: { $gte: 12 } });4. Model.findById(): This query takes the id as the parameter and then returns the entry in the database if it exists matches.
Student.findById('613b3c3d4f1a2b4dbb1b0b9f');5. Model.findByIdAndDelete(): This query takes the id as the parameter and then deletes the entry in the database if it exists matches.
Student.findByIdAndDelete('613b3c3d4f1a2b4dbb1b0b9f');6. Model.findByIdAndRemove(): This query takes the id as the parameter and then removes the entry in the database if it exists and then returns it to the callback function.
Student.findByIdAndRemove('613b3c3d4f1a2b4dbb1b0b9f');7. Model.findByIdAndUpdate(): This query takes the id and the update parameters and values as the parameter and then updates the entry in the database if it exists.
Student.findByIdAndUpdate('613b3c3d4f1a2b4dbb1b0b9f', { age: 20 });8. Model.findOne(): This query takes the parameters of any field that matches and then returns any one of the entries in the database that matches.
Student.findOne({ name: 'John' });9. Model.findOneAndDelete(): This query takes the parameters of any field that matches and then returns and deletes any one of the entries in the database that matches.
Student.findOneAndDelete({ name: 'John' }); 10. Model.findOneAndRemove(): This query takes the parameters of any field that matches and then returns and removes any one of the entries in the database that matches.
Student.findOneAndRemove({ name: 'John' });11. Model.findOneAndReplace(): This query takes the parameters of any field and the replace document and then replaces any one of the entries in the database that matches.
Student.findOneAndReplace({ name: 'John' }, { name: 'John Doe', age: 22 });12. Model.findOneAndUpdate(): This query takes the parameters of one or more fields and the updated fields and values and then updates any one of the entries in the database that matches.
Student.findOneAndUpdate({ name: 'John' }, { age: 21 });13. Model.replaceOne(): This query takes the parameters as a filter and the replacement document and then replaces any one of the entries in the database that matches.
Student.replaceOne({ name: 'John' }, { name: 'John Doe', age: 22 });14. Model.updateMany(): This query takes the parameters as a filter and the updating fields and values and then updates all of the entries in the database that matches.
Student.updateMany({ age: { $gt: 12 } }, { highschool: true });15. Model.updateOne(): This query takes the parameters as a filter and the updating fields and values and then updates any one of the entries in the database that matches.
Student.updateOne({ name: 'John' }, { $set: { highschool: true } });Creating Application and Using Mongoose Queries
We will create a Student model that will contain the fields name, age and date of birth. Then we will save three documents to MongoDB using mongoose. Finally, we are going to update them if their age is greater than 12. Node.js and NPM are used in this example, so it is required to be installed.
Step 1: Initialize Your Project
Start by creating a folder and initializing your Node.js project:
npm initStep 2: Install mongoose
Install Mongoose to interact with your MongoDB database:
npm i mongooseProject Structure: The project structure is as follows:

Example: Creating and Updating Student Records
const mongoose = require("mongoose");
// Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks",);
// Creating Schema
const studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, default: 8 },
highschool: { type: Boolean, default: false },
});
// Student model
const Student = mongoose.model("Student", studentSchema);
// Creating Student document from Model
// function to save in database
const saveStudent = async (name, age) => {
let s = new Student({
name: name,
age: age,
});
await s.save();
console.log("student document saved in database\n
Student name:", s.name);
};
const updateHighSchool = async () => {
await Student.updateMany(
{ age: { $gt: 12 } },
{ highschool: true });
console.log("Updated student fields");
};
const start = async () => {
await saveStudent("Ajay", 5);
await saveStudent("Rajesh", 13);
await saveStudent("Manav", 15);
updateHighSchool();
};
start();
In this example:
- Create a SchemaType and a Model for students.
- Add three student documents with sample values.
- Use the save() function to store the documents in the database.
- Instead of saving each document separately, create a function to save multiple students at once.
- Write a query to find students with age ≥ 12.
- Update those students by setting highschool = true
Step 4: Run the Application
Now run the code using the following command in the Terminal/Command Prompt to run the file.
node index.jsOutput:

The documents in the MongoDB are as follows: Two students are in high school but not Ajay. Previously all were set to false but two of them got updated.
