DEV Community

Cover image for MongoDB CRUD Operations
Tahmina Nasrin Tazin
Tahmina Nasrin Tazin

Posted on

MongoDB CRUD Operations

MongoDB is a NoSQL database program that is a document-oriented database program. It has gained popularity as NoSQL databases are handy for working with large sets of data. Simple CRUD operations have been described below.

Create
To insert a single document, the insertOne() method can be used. The document object to be inserted has to be passed as the argument. If the insertion is successful, an insertedId field is appended to the object passed in the method. This value is used as the _id in the database.

      const newProduct = {
    name: ‘Flormar Lipstick’,
    price: ‘45.00’,
}
      const result = await lipsticksCollection.insertOne(newProduct);
Enter fullscreen mode Exit fullscreen mode

Retrieve
To retrieve a single document, the findOne() method can be used. The document to be searched has to be queried and the query has to be passed as the argument.

const id = req.params.id;
      const query = { _id: ObjectId(id) };
      const product = await lipsticksCollection.findOne(query);
Enter fullscreen mode Exit fullscreen mode

Update
To update a single document, the updateOne() method can be used. A filter document and an update document has to be passed as argument. The purpose of the filter document is to find the document to be updated. A third argument named options can be passed as well to specify any other options if needed.

const id = req.params.id;
      const filter = { _id: ObjectId(id) };
      const options = { upsert: true };

      const updateDoc = {
        $set: {
          status: "Shipped",
        },
      };
      const result = await ordersCollection.updateOne(
        filter,
        updateDoc,
        options
      );
Enter fullscreen mode Exit fullscreen mode

Delete
To delete a single document, the deleteOne() method can be used. The document to be deleted has to be queried and the query has to be passed as the argument. If the deletion is successful, then the deletedCount is set to 1, which can be checked to test whether the operation was successful.

const id = req.params.id;
      const query = { _id: ObjectId(id) };
      const result = await lipsticksCollection.deleteOne(query);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)