Operations for MongoDB Document – Insert, Query, Update, Delete

FREE Online Courses: Click, Learn, Succeed, Start Now!

In the last tutorial, we had seen projection in MongoDB. Now, we will be looking at different operations, which we can perform on MongoDB Document like, insert, query, update and delete. We will be looking at each operation separately in this tutorial with their syntax and examples.

Operations for MongoDB Document

In this MongoDB Document Tutorial, we will study: How can we insert, delete, update and query a MongoDB Document, with their syntax, SQL commands, and examples. So, let’s start it.

i. How MongoDB Insert a Document?

When we want to insert any value in our document we will use this operation.

When you want to insert a single value in the document then you will be using this command.

db.collection.insertOne()

In the below example we will insert a MongoDB document in the collection named “examples”. Here if we don’t specify the _id field then MongoDB by itself adds the _id field with an ObjectId value to the document that we have created.

db.examples.insertOne(
{ item: "c", qty: 100, tags: ["cotton"], size: { h: 30, w: 37.5, uom: "cm" } }
)

Here insertOne() returns a document that includes newly inserted document’s _id value. To retrieve the document that you have just inserted write this command:

db.examples.find( { item: "c" } )

The above example was for when you want to insert a single value. But what if you want to insert many values at a time. So for that also MongoDB has a solution. You can use the following command to insert many values at a time:

db.collection.insertMany()

In the example given below we are going to add 3 documents in the example collection.

db.examples.insertMany([
{ item: "j", qty: 25, tags: ["blank", "white"], size: { h: 17, w: 28, uom: "cm" } },
{ item: "mats", qty: 85, tags: ["blue"], size: { h: 29.9, w: 39.5, uom: "cm" } },
{ item: "mouse", qty: 25, tags: ["gel", "grey"], size: { h: 27, w: 29.85, uom: "cm" } }
])

Here insertMany() returns a document that includes the newly inserted _id field values for the same document. To retrieve the inserted values of documents use the following command:

db.examples.find( {} )

ii. How MongoDB Query a Document?

Here we will understand query operations in MongoDB by using an example. In the below example we will be using example collection.

db.examples.insertMany([
{ item: "j", qty: 25, size: { h: 18, w: 28, uom: "cm" }, status: "A" },
{ item: "notebooks", qty: 50, size: { h: 9.5, w: 19, uom: "in" }, status: "A" },
{ item: "papers", qty: 100, size: { h: 11.5, w: 11, uom: "in" }, status: "D" },
{ item: "pl", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "po", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
  • How to select all the MongoDB Documents in a Collection?

When we want to select all documents in a collection, we can pass an empty document to the find method.

db.examples.find( {} )

This operation is similar to SQL command as follows:

SELECT * FROM example
  • Specify Equality Condition

We can use <field>:<value> expressions to specify equality condition.

{ <field1>: <value1>, ... }

Now we will understand this by our above example:

db.examples.find( { status: "D" } )

This is similar to SQL command as follows:

SELECT * FROM example WHERE status = "D"
  • How to specify conditions using query operators?

The syntax for the following operation is as follows:

{ <field1>: { <operator1>: <value1> }, ... }

Now we will understand this syntax with our example as follows:

db.example.find( { status: { $in: [ "A", "D" ] } } )

In the above example, we are retrieving all the documents from example collection where the status is equal to “A” or”D”.

This is similar to SQL command as follows:

SELECT * FROM example WHERE status in ("A", "D")
  • Specify AND Condition

Here we will be performing operations on more than one documents. In the AND operation all the conditions should be true otherwise the command will not be executed.

db.examples.find( { status: "A", qty: { $lt: 30 } } )

In the above example, all the documents from example collection where the status equals “A” and qty is less than ($lt) 30.

This is similar to SQL command as follows:

SELECT * FROM example WHERE status = "A" AND qty < 30
  • Specify OR Condition

In the logical OR operation, at least one condition should be true so that we can execute the operation.

In the below example we will retrieve all the documents in which status is equal to “A” or qty is less than 30.

db.examples.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )

This is similar to SQL command as follows:

SELECT * FROM example WHERE status = "A" OR qty < 30
  • Specify AND as well as OR Condition

In this compound query only those documents will be printed in output where status is equal to “A” and either qty is less than 30 or item name starts with “p”.

db.examples.find( {
status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )

This is similar to SQL command as follows:

SELECT * FROM example WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")

iii. How MongoDB Update a Document?

For the understanding update in MongoDB documents we will use the following example:

db.examples.insertMany( [
{ item: "c", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
{ item: "j", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "mats", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
{ item: "mousepads", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
{ item: "notebooks", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ item: "papers", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "pl", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "po", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
{ item: "sk", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "sketches", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
] );
The syntax for doing an update in our document is as follows:
{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}
  • How to Update a Single MongoDB Document?

Here we are updating a single document in MongoDB from the whole collection. The syntax followed with the above-given example is as follows:

db.examples.updateOne(
{ item: "papers" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)

Here the document will be updated where an item is equal to “papers”.

  • How to Update a Multiple MongoDB Documents?

Here the update will reflect on more than one document.

db.examples.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)

Here, the documents of example collection will be updated where qty is less than 50.

iv. How MongoDB Update a Document?

For understanding this process we will be taking help of this example

db.examples.insertMany( [
{ item: "j", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebooks", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ item: "papers", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "pl", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "po", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
] );

The syntax for deleting MongoDB documents is as follows:

db.examples.deleteMany({})
  • How to delete only one MongoDB document that matches a condition?

If you wish to delete a single document from the collection then you will have to use the following command:

db.examples.deleteOne( { status: "D" } )

Here the first document with status D will be deleted.

  • How to delete all documents that match a condition?

Here all the documents will be deleted which are matching the condition given in the query. This can be useful at places where you want to delete many documents at a time.

db.examples.deleteMany({ status : "A" })

Here all the MongoDB documents from example collection will be deleted where status is equal to A.

So, this was all about operations on MongoDB Document. Hope you liked our explanation.

Summary

Hence, we have studied the different operations that can be performed on a document in MongoDB. The operations insert, query, update and delete. Now in the next tutorial, we will have a look how to create a backup in MongoDB.

Still, have a query? Feel free to ask in the comment box.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

follow dataflair on YouTube

1 Response

  1. Anil Kumar says:

    If you can add like what will happened db.examples.deleteOne( { } ). It will delete first doc in the collection

Leave a Reply

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