How to use updateOne() Method with $unset Operator In MongoDB
- The updateOne() method is used to update a single document that matches the specified filter criteria in a collection. If multiple documents match the filter, only the first document encountered is updated.
Syntax:
Model.updateOne(
<filter>,
<update>,
[options],
[callback]
)
Explanation:
- Model: This is the Mongoose model that we want to update.
- filter: This is the filter that selects the document to update. It can be an object that specifies the query criteria.
- update: This is the update operator that specifies the changes to make to the document. In the example, we used `$unset` operator to delete the `address` field.
- options: This is an optional object that contains options for the update operation. For example, we can specify the `upsert` option to create a new document if no document matches the filter.
- callback: This is an optional callback function that is called when the update operation is complete. It takes an error object and a result object as arguments
Let’s set up an Environment
To understand How to Delete a key from a MongoDB document using Mongoose we need a collection and some documents on which we will perform various queries. Here we will consider a collection called courses which contains information like course name, Instructore name, fees and date of the courses in various documents.
Example 1: Removing the Fees key from the document
Add the code into the queryData.js file and run using node queryData.js command
Query:
const mongoose = require("mongoose");
const Course = require("./model");
const db = require("./dbConnect");
async function deleteKeyFromDocument() {
try {
await Course.updateOne({}, { $unset: { Fees: 1 } });
console.log("Key deleted successfully from document");
const courses = await Course.find({});
console.log("Courses after deletion:");
console.log(courses);
} catch (error) {
console.error("Error deleting key:", error);
} finally {
mongoose.disconnect();
}
}
deleteKeyFromDocument();
Output:
Explanation:
- The async function uses the Course.updateOne() method to update the document in the collection by removing the Fees key from first document. with the help of the $unset operator.
- After the update operation, the function logs a success message to the console and then uses Course.find({}) to retrieve all the courses from the database. These courses are then logged to the console.
Example 2: Removing the Instrctutor key from the document
Query:
const mongoose = require("mongoose");
const Course = require("./model");
const db = require("./dbConnect");
async function deleteKeyFromDocument() {
try {
await Course.updateOne({}, { $unset: { Instructor: 1 } });
console.log("Key deleted successfully from document");
const courses = await Course.find({});
console.log("Courses after deletion:");
console.log(courses);
} catch (error) {
console.error("Error deleting key:", error);
} finally {
mongoose.disconnect();
}
}
deleteKeyFromDocument();
Output:
Explanation:
- The async function uses the Course.updateOne() method to update the document in the collection by removing the Instructor key from the first document. with the help of the $unset operator.
- After the update operation, the function logs a success message to the console and then uses Course.find({}) to retrieve all the courses from the database. These courses are then logged to the console.
How to Delete a Key from a MongoDB Document using Mongoose?
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. When working with MongoDB using Mongoose, a MongoDB object modeling tool designed to work in an asynchronous environment and developers encounter scenarios where they need to delete a key from a document.
In this article, We will learn about the process of deleting a key from a MongoDB document using Mongoose by understanding the various methods along with the examples and so on.