Mongoose is a powerful object modeling tool for MongoDB and Node.js. It provides a schema-based solution to model your data, simplifying interactions with MongoDB databases. Mongoose queries are essential for performing CRUD (Create, Read, Update, Delete) operations, making them indispensable for any database-driven application. This article covers various Mongoose queries and how to use them effectively.
What are Mongoose Queries?
Mongoose Queries are different static helper functions to carry out CRUD (Create Read Update and Delete) operations which are very important for any database. The static helper functions return a mongoose query object. The mongoose query is carried out first asynchronously and then calls the callback function passed to it. An alternative way is to use the synchronous function which is responsible for executing the query.
Mongoose queries are commonly used to:
- Retrieve documents from MongoDB (Read).
- Add new documents (Create).
- Modify existing documents (Update).
- Remove documents (Delete).
Each query function is versatile and can be customized with parameters to match specific conditions. The following example demonstrates how to use the findOneAndUpdate
query to update a student's information in a MongoDB collection. Here’s the basic syntax:
Syntax:
const Student = mongoose.model('Student', studentSchema);
Student.findOneAndUpdate({ name: 'John' },
function (err, student) {
if (err) return handleError(err);
else{
// Updated successfully
}
});
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 init
Step 2: Install mongoose
Install Mongoose to interact with your MongoDB database:
npm i mongoose
Project Structure: The project structure is as follows:
Example: Creating and Updating Student Records
Create a schematype, then a model, and create three different documents with some values. Then call the save function to save the document. We can create a save function to save student documents rather than creating individual documents. Then we will call a function that will query the documents having age greater than or equal to 12. We will make them study in high school as a field highschool=true.
Code:
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();
Step 4: Run the Application
Now run the code using the following command in the Terminal/Command Prompt to run the file.
node index.js
Output:
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.
Conclusion
Mongoose queries are essential for interacting with MongoDB databases. They offer a variety of methods to manage data, from creating documents to updating and deleting them. Mongoose’s flexibility in querying and updating documents allows for precise control over the data. By mastering Mongoose queries, we can efficiently handle our MongoDB operations and ensure our application works seamlessly with the database. By using Mongoose's powerful features, we can build more robust and scalable Node.js applications.
Similar Reads
Mongoose Tutorial
Mongoose is a popular ODM (Object Data Modeling) library for MongoDB and Node.js that simplifies database interactions by providing a schema-based solution to model application data. It is widely used to build scalable, structured, and efficient database-driven applications.Built on MongoDB for seam
6 min read
Mongoose Schemas
Mongoose Schemas Creating a Model
Mongoose is one of the most popular Object Data Modeling (ODM) libraries for MongoDB, providing schema-based solutions to model our application's data. This allows us to define the structure of documents within a MongoDB collection, including validation, typecasting, and other powerful features that
5 min read
Mongoose Schemas and Indexes
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB in a Node.js environment. It provides a straightforward way to interact with MongoDB, including features like schema definition, model creation, and database query handling. One key feature of Mongoose is its ability to create and
5 min read
Mongoose Schemas Instance methods
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB, designed to work in a Node.js environment. One of the key features of Mongoose is its ability to define instance methods on schema objects, which allow you to perform operations on individual documents. This guide will explore Mo
5 min read
Mongoose Schemas Ids
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose automatically adds an _id property of type ObjectId to a document when it gets created. This can be overwritten with a custom id as well, but note that without an id, mongoose doesn't allow us to save or create a
2 min read
Mongoose Schemas Virtuals
Virtuals are a powerful feature in Mongoose that allow us to add attributes to documents without actually storing them in the database. These properties can be dynamically calculated based on other fields, making it easier to manage and manipulate your data. In this comprehensive article, weâll dive
6 min read
Mongoose Schemas Aliases
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schemas Aliases help in converting a short property name in the database into a longer, more verbal, property name to enhance code readability. Creating node application And Installing Mongoose: Step 1: Create a
2 min read
Mongoose Schemas With ES6 Classes
Mongoose is a MongoDB object modeling and handling for a node.js environment. To load Mongoose schema from an ES6 Class, we can use a loadClass() method which is provided by Mongoose Schema itself. By using loadClass() method: ES6 class methods will become Mongoose methodsES6 class statics will bec
2 min read
Mongoose Schemas Query Helpers
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schema Query Helpers are like instance methods for Mongoose queries. These query helpers can be used to filter out mongoose query results or perform additional operations on the existing result. Creating node appl
3 min read
Mongoose Documents
Mongoose Documents
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js, making it easier to interact with MongoDB databases. It provides a structured way to handle data, perform validation, and manage documents in MongoDB with ease. In this article, we will explain Mongoose Documents, how
5 min read
Mongoose Documents vs Models
Mongoose, a popular Node library, is widely used for interacting with MongoDB, a NoSQL database. Mongoose simplifies the process of working with MongoDB by providing an object data modeling (ODM) framework. In the Mongoose ecosystem, two key concepts are Documents and Models. In this article, we'll
4 min read
Mongoose Documents Updating Using save()
An important aspect of a mongoose model is to save the document explicitly when changes have been made to it. This is done using the save() method. In this article, we will see its uses and see the things we should keep in mind while saving our document.We will take the help of an example to underst
5 min read
Mongoose Queries
Mongoose Queries
Mongoose is a powerful object modeling tool for MongoDB and Node.js. It provides a schema-based solution to model your data, simplifying interactions with MongoDB databases. Mongoose queries are essential for performing CRUD (Create, Read, Update, Delete) operations, making them indispensable for an
7 min read
Mongoose deleteMany() Function
The deleteMany() function is employed to remove all documents meeting specified conditions from a collection. Unlike the remove() function, deleteMany() deletes all matching documents without considering the single option. This method is essential for Node.js developers working with Mongoose, as it
4 min read
Mongoose Queries Model.replaceOne() Function
The Queries Model.replaceOne() function of the Mongoose API is used to replace an existing document with the given document. It replaces only the first document that is returned in the filter. Syntax: Model.replaceOne( filter, doc, options, callback ) Parameters: It accepts the following 4 parameter
3 min read
Find() Method in Mongoose
The Mongoose find() method is one of the most widely used methods for querying MongoDB collections in Node.js. It provides a flexible and powerful way to fetch data from your MongoDB database. In this article, we will explore the find() method in detail, its syntax, parameters, and how to implement
5 min read
FindById Method in Mongoose
The findById() method in Mongoose is one of the most commonly used methods for retrieving a document by its unique identifier (_id) in a MongoDB collection. This article will cover everything we need to know about how to use the findById() method, including syntax, examples, installation, and troubl
4 min read
Mongoose QueriesModel.findByIdAndDelete() Method
The Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo
4 min read
Mongoose findByIdAndRemove() Function
MongoDB is the most used cross-platform, document-oriented database that provides, high availability, high performance, and easy scalability. MongoDB works on the concept of collecting and documenting the data. findByIdAndRemove() stands proud as a convenient way to discover a file by its specific i
2 min read
Mongoose QueriesModel.findByIdAndDelete() Method
The Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo
4 min read
FindOne() Method in Mongoose
The findOne() method in Mongoose is one of the most commonly used functions for querying data from a MongoDB database. It provides a simple and efficient way to retrieve a single document that matches a specified query condition. This article will explore how to use the findOne() method, explain its
5 min read
Mongoose findOneAndDelete() Function
The findOneAndDelete() function in Mongoose is an efficient and commonly used method to find a document based on a specified filter and delete it from a MongoDB collection. This method simplifies the process of removing documents and is a key tool for developers working with Node.js and MongoDB. In
5 min read
Mongoose | findOneAndRemove() Function
The findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element. Installation of mongoose module:You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongooseAfter installin
2 min read
Mongoose | findOneAndReplace() Function
When working with MongoDB in Node.js, Mongoose is an essential tool for schema-based modeling and database operations. One of the most powerful and frequently used functions in Mongoose is findOneAndReplace(). This function helps in finding a document and replacing it with a new one. But how exactly
5 min read
Mongoose Queries Model.findOneAndUpdate() Function
The Queries Model.findOneAndUpdate() function of the Mongoose API is used to find and update an existing document with the information mentioned in the "update" object. It finds and updates only the first document that is returned in the filter. Syntax: Model.findOneAndUpdate(conditions, update, opt
3 min read
Mongoose Document Model.replaceOne() API
The Model.replaceOne() method of the Mongoose API is used to replace any one document in a collection. This method works the same as the update method but it replaces MongoDB's existing document with the given document with any atomic operator i.e $set. Syntax: Model.replaceOne() Parameters: Â The Mo
3 min read
updateMany() Method in Mongoose
In Mongoose, the updateMany() method is a powerful tool for performing bulk updates in MongoDB. It updates multiple documents that match a specified condition, applying the changes to all the matched documents in a single operation. Unlike updateOne(), which updates only the first matching document,
4 min read
Mongoose Queries Model.updateOne() Function
The Queries Model.updateOne() function of the Mongoose API is used to update an existing document with the information mentioned in the "update" object. It updates only the first document that is returned in the filter. Syntax: Model.updateOne(filter, update, options, callback ) Parameters: It accep
3 min read