Categories
MongoDB Node.js Basics

Node.js Basics — Deleting and Updating MongoDB Documents

Spread the love

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Delete a Document

We can delete a document within our MongoDB collection.

To do that, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

const pizzaDocuments = [
  { name: "Sicilian pizza", shape: "square" },
  { name: "New York pizza", shape: "round" },
  { name: "Grandma pizza", shape: "square" },
];

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany(pizzaDocuments);
    console.log(result)
    const deleteResult = await testCollection.deleteOne({ name: { $type: "string" } });
    console.log(deleteResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We pass in a query into the deleteOne method to delete all the entries with the name that has type string.

Also, we can delete all the entries with the name set to type string with the deleteMany method:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

const pizzaDocuments = [
  { name: "Sicilian pizza", shape: "square" },
  { name: "New York pizza", shape: "round" },
  { name: "Grandma pizza", shape: "square" },
];

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertMany(pizzaDocuments);
    console.log(result)
    const deleteResult = await testCollection.deleteMany({ name: { $type: "string" } });
    console.log(deleteResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

Change a Document

We can update a document with thw updateOne method.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

const filter = { foo: 'bar' };
const updateDocument = {
  $set: {
    foo: 'baz',
  },
};

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.updateOne(filter, updateDocument);
    console.log(result)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call the updateOne method to find the item with the query object in the first argument.

The 2nd argument is the document to update the item with.

The $set property indicates that we want to add or update the key-value pair in the object we set as its value.

Update Arrays in a Document

We can update arrays in a document by accessing its property.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertOne({
      name: "Popeye",
      address: "1 Sweethaven",
      items: [
        {
          type: "pizza",
          size: "large",
          toppings: ["garlic, spinach"],
        },
        {
          type: "calzone",
          toppings: ["ham"],
        },
      ],
    });
    console.log(result)
    const query = { name: "Popeye" };
    const updateDocument = {
      $set: { "items.0.toppings": "veggie" }
    };
    const updateResult = await testCollection.updateOne(query, updateDocument);
    console.log(updateResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We call insertOne to add the entry we want into our collection.

Then we define the updateDocument object with the $set property to set the item we want.

items.0.toppings will get the toppings property of the first entry ofitems array and update it.

To match all array elements, we can use the $[] positional operator:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    await client.connect();
    const testCollection = await client.db("test").collection('test');
    const result = await testCollection.insertOne({
      name: "Popeye",
      address: "1 Sweethaven",
      items: [
        {
          type: "pizza",
          size: "large",
          toppings: ["garlic, spinach"],
        },
        {
          type: "calzone",
          toppings: ["ham"],
        },
      ],
    });
    console.log(result)
    const query = { name: "Popeye" };
    const updateDocument = {
      $set: { "items.$[].toppings": "veggie" }
    };
    const updateResult = await testCollection.updateOne(query, updateDocument);
    console.log(updateResult)
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

Now both items in the items array has 'veggie' appended into it.

Conclusion

We can delete a document and update an array in an existing document with the MongoDB driver.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *