Comprehensive Guide: Remove a Field Completely from a MongoDB Document

In this tutorial, I am going to explain how you can remove a field completely from a MongoDB document with help of the Mongoose ODM in a Nodejs application.

Developing an application or maybe learning to develop one involves a lot of trying and testing. Sometimes, you are unsure as to what features your applications must-have. It is sometimes difficult to decide.

Then, there are times when you want to change things altogether or maybe even remove them for good. Well, this also involves a point when you might want to remove a field completely from a MongoDB document. Or, maybe even all your documents.

In this guide, I will demonstrate with an example how to remove a field completely from a single and multiple MongoDB documents. You can seek help from this guide if you want to remove a field completely from the already existing documents as well as the new and fresh ones that will come up.

So, let us get started.

How to Remove a Field Completely from a MongoDB Document with Mongoose

To demonstrate how to remove a field completely from a single MongoDB document, I will create a mini Nodejs application and take the help of Mongoose to do so.

Follow the steps below to get started.

  • Create a Nodejs project directory and move into it:
mkdir newNodeProject
cd newNodeProject
  • Create your Nodejs project inside the directory like this:
npm init -y

After you run this command, you should then see a package.json file automatically created in the directory. This file will allow you to change the entry point file name.

Simply look for the “main” key in the object, and change its value to the file name you prefer. I will name mine app.js

  • Next, create the entry point JavaScript file:
touch app.js
  • Let us install all the required NPM packages for our project:
npm i express mongoose
  • Next, we need to import all of those packages we installed. All our installed NPM packages are stored inside the node_modules directory. Paste this code into the app.js file.
const express = require('express');
const app = express();
const mongoose = require('mongoose');
  • Next, we shall set up a connection with a local MongoDB database. We will use Mongoose for this:
mongoose.connect('mongodb://localhost:27017/farmDB', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log(`CONNECTED TO MONGO!`);
    })
    .catch((err) => {
        console.log(`OH NO! MONGO CONNECTION ERROR!`);
        console.log(err);
    })
  • Next, at the end of the app.js file, I will set up localhost port for my app server to listen:
app.listen(8000, () => {
    console.log('Connected to PORT 8000...');
})
  • Next, in your project directory, create a directory named models.
mkdir models
  • Now, create a new file inside the directory named produce.js, or anything you’d like.
touch models/produce.js
  • We shall now import Mongoose here as well to be able to create a schema for our farm produces and the associated model.
const mongoose = require('mongoose');

const produceSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true,
        min: 0
    },
    category: {
        type: String,
        lowercase: true,
        enum: ['fruit', 'vegetable', 'dairy']
    },
});

const Produce = mongoose.model('Produce', produceSchema);
  • To remove a field completely from a MongoDB document we need to have a few documents in our database. I have created and added a few beforehand and this is what it looks like:
{ "_id" : ObjectId("6054f4ba0e761c066439114b"), "name" : "Fairy Eggplant", "price" : 1, "category" : "vegetable", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114c"), "name" : "Organic Goddess Melon", "price" : 4.99, "category" : "fruit", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114d"), "name" : "Organic Mini Seedless Watermelon", "price" : 3.99, "category" : "fruit", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114e"), "name" : "Organic Celery", "price" : 1.5, "category" : "vegetable", "__v" : 0 }
{ "_id" : ObjectId("6054f4ba0e761c066439114f"), "name" : "Chocolate Whole Milk", "price" : 2.69, "category" : "dairy", "__v" : 0 }
  • Let’s say we do not want the category field anymore on one of our documents. We will be overwriting our document using $unset. We must first execute this code:
Produce.update({ name: 'Organic Goddess Melon' }, {
    $unset: { category: 1 }
}).exec(function (err) {
    console.log(err);
});

This way we have successfully learned to remove a field completely from a single document. However, this will not remove the field from other documents. To do so, see the next section below.

How to Remove a Field Completely from All MongoDB Documents with Mongoose

To be able to remove a field completely from all MongoDB documents with the help of Mongoose, simply take the help of the example below.

Produce.update({}, {
    $unset: { category: 1 }
},
    {
        multi: true
    }).exec(function (err) {
        console.log(err);
    });

Notice we have passed the “multi” option as true. This way, we have successfully learned to remove a field completely from all documents. You can now safely remove the field from the schema too so no new documents come from that field.

Read More: Easy Guide to Delete Everything in a MongoDB Database

Conclusion

In this guide, I have demonstrated with examples how to remove a field completely from a single and multiple MongoDB documents.

Noteworthy References

Aneesha S
Aneesha S
Articles: 171