Progress

MongoDB Example Query for CRUD Operations

Introduction: This is beginners friendly CRUD (ceate, read, update, delete) operations tutorials for MongoDB shell. The article contains example queries for MongoDB CRUD operations using shell commands.

MongoDB Example Query for CRUD Operations

MongoDB CRUD operations mean basic create, read, update and delete operations. They are the very basics of MongoDB and the best way to know how to interact with the shell commands.

In this tutorial, I assume that you have installed MongoDB and you can use its shell.

Type mongo --version to verify it and mongo to enter in the shell.

Execute these commands to use a temporary database for this article.

use hc_ecommerce

Insert a Document in MongoDB Collection - Create Operation

The create operation means to create a new document in the collection. If the collection does not exist then the insert operation will automatically create it.

It is good practice to create collection with proper validation, it helps to build a predictable database.

MongoDB provides two methods to insert a document in any collection.

  • The insertOne method
  • The insertMany method

InsertOne

If we need to insert only one document to the collection then we can use insertOne method.

Here is the general syntax of the insertOne method in MongoDB.

db.collectionName.insertOne(documentObject, {writeConcern: document});

Here is an example query for MongoDB insertOne method at the products collection.

db.products.insertOne(
    {
        name: "Apple", 
        quantity: 10, 
        price: 10, 
        seller: { 
            name: "Roadside Shop",
            address: "54 west Gomti Nagar, Lucknow",
            phone: "0000000000"
        }
    }
);

If it returns a message something like this then the insertion was successful.

{
	"acknowledged" : true,
	"insertedId" : ObjectId("5ee89e61158fd089943e297b")
}

InsertMany

There are situations when we want to insert multiple documents in a collection. Then, instead of multiple insertOne we can simply use InsertMany and pass array of documents.

The general syntax for insertMany is explained below.

db.collectionName.insertMany([...array of document objects], writeConcern: document, ordered: boolean); 

Here is an example query in MongoDB shell to insert multiple product documents to the products collection.

db.products.insertMany(
    [
        {
            name: "Banana", 
            quantity: 10, 
            price: 10, 
            seller: { 
                name: "Roadside Shop",
                address: "54 west Gomti Nagar, Lucknow",
                phone: "0000000000"
            }
        },
        {
            name: "Orange", 
            quantity: 10, 
            price: 10, 
            seller: { 
                name: "Roadside Shop",
                address: "54 west Gomti Nagar, Lucknow",
                phone: "0000000000"
            }
        }
        
    ]
);

Here is the output on the terminal after successful insertion.

{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("5ee8a11e158fd089943e297c"),
		ObjectId("5ee8a11e158fd089943e297d")
	]
}

Read Operation in MongoDB Shell

Read operation in MongoDB means to fetch or retrieve the documents of the collection. MongoDB provides two methods to get documents of a particular collection.

  • The find method
  • findOne method

Find

The find method returns a cursor object which iterates through all the documents of the database.

Here is a general syntax for the find query in MongoDB shell.

db.collectionName.find(query, projection)

Here is a MongoDB example query to read documents from products collection.

db.products.find()

By default, find will query and return first 20 documents and then we can type it to continue iteration and get more results.

It will output all the documents in the products collection of the database.

{ "_id" : ObjectId("5ee89e61158fd089943e297b"), "name" : "Apple", "quantity" : 10, "price" : 10, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }
{ "_id" : ObjectId("5ee8a11e158fd089943e297c"), "name" : "Banana", "quantity" : 10, "price" : 10, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }
{ "_id" : ObjectId("5ee8a11e158fd089943e297d"), "name" : "Orange", "quantity" : 10, "price" : 10, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }

We can chain it with limit cursor modifier to pass custom limit on the number of documents it will return.

db.products.find().limit(2);

It will return only the first two documents of the collection.

{ "_id" : ObjectId("5ee89e61158fd089943e297b"), "name" : "Apple", "quantity" : 10, "price" : 10, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }
{ "_id" : ObjectId("5ee8a11e158fd089943e297c"), "name" : "Banana", "quantity" : 10, "price" : 10, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }

Limit and skip are very powerful cursor modifiers which can create complex functionality easily.

Example: To implement pagination, we can skip 20 documents and limit next 20 documents for the second page.

FindOne

The findOne method of MongoDB returns only one document of the collection based on the query condition.

Here is a MongoDB example query that will return the first document with the name Applefrom the collection.

db.products.findOne({name: "Apple"});

The above query will return the following output.

{
	"_id" : ObjectId("5ee89e61158fd089943e297b"),
	"name" : "Apple",
	"quantity" : 10,
	"price" : 10,
	"seller" : {
		"name" : "Roadside Shop",
		"address" : "54 west Gomti Nagar, Lucknow",
		"phone" : "0000000000"
	}
}

Update Operation in MongoDB Shell

The update operation in MongoDB changes or updates existing documents in a collection.

MongoDB provides three methods to update documents in a collection.

  • The updateOne method
  • updateMany
  • replaceOne

UpdateOne

If we want to update only one document then we can use updateOne method.

The general syntax of updateOne method in MongoDB.

db.collectionName.updateOne(filter, update, options);

Here is a MongoDB example query to update the price of a product.

db.products.updateOne({name: "Apple"}, {$set: {price: 50}});

The above query will return the following message. Now if we try to read the document we will see the price is updated (now apples are costly :).  

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }


> db.products.findOne({name: "Apple"});
{
	"_id" : ObjectId("5ee89e61158fd089943e297b"),
	"name" : "Apple",
	"quantity" : 10,
	"price" : 50,
	"seller" : {
		"name" : "Roadside Shop",
		"address" : "54 west Gomti Nagar, Lucknow",
		"phone" : "0000000000"
	}
}

Note that it will update only one document (the first occurrence) even if there are multiple documents satisfying the query condition.  

UpdateMany

If you want to update many documents then updateMany method is suitable. It will update all the documents matching the query condition.

Here is a MongoDB example query to update the prices of all products whose quantity is less than 20.

db.products.updateMany({quantity: {$lt: 20}}, {$set: {price: 15}});

The above query returns the following result and all the documents whose quantity was less than 20 have updated their price to 15.

{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }

> db.products.find()
{ "_id" : ObjectId("5ee89e61158fd089943e297b"), "name" : "Apple", "quantity" : 10, "price" : 15, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }
{ "_id" : ObjectId("5ee8a11e158fd089943e297c"), "name" : "Banana", "quantity" : 10, "price" : 15, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }
{ "_id" : ObjectId("5ee8a11e158fd089943e297d"), "name" : "Orange", "quantity" : 10, "price" : 15, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }

ReplaceOne

The replaceOne query replaces a document satisfying query condition with another.

The general syntax of the replaceOne MongoDB query is:

db.collectionName.replaceOne(filter, replacement, options);

Here is an example MongoDB example query to replace the product having name: "Orange" with another product.

db.products.replaceOne({name: "Orange"}, {name: "Mango", quantity: 12, price: 18, seller: {name: "Roadside Shop", address: "54 west Gomti Nagar, Lucknow", phone: "0000000000"}});

The above query will return the following output.

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Now, if we try to run find method then we will see that Orangeproduct is replaced with new Mangoproduct.

> db.products.find()
{ "_id" : ObjectId("5ee89e61158fd089943e297b"), "name" : "Apple", "quantity" : 10, "price" : 15, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }
{ "_id" : ObjectId("5ee8a11e158fd089943e297c"), "name" : "Banana", "quantity" : 10, "price" : 15, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }
{ "_id" : ObjectId("5ee8a11e158fd089943e297d"), "name" : "Mango", "quantity" : 12, "price" : 18, "seller" : { "name" : "Roadside Shop", "address" : "54 west Gomti Nagar, Lucknow", "phone" : "0000000000" } }

Delete Operation in MongoDB Shell

The delete operation removes the documents from a collection. MongoDB provides two methods to delete documents from a collection.

  • deleteOne
  • deleteMany

DeleteOne

If we need to remove only one document from the collection then we can use deleteOne method.

The general syntax for deleteOne method in MongoDB is:

db.collectionName.deleteOne(filter, {writeConcern, collation});

Here is a sample MongoDB example query to delete a document with name: banana query condition.

db.products.deleteOne({name: "Banana"});

The above query will give the following output after a successful deletion of the document.

{ "acknowledged" : true, "deletedCount" : 1 }

DeleteMany

If we need to delete multiple documents in a collection then instead of executing deleteOne multiple times  we can simply use deleteMany method.

Here is a sample MongoDB example query to delete all documents whose quantity is less than 20.

db.products.deleteMany({quantity: {$lt: 20}});

The above query will return the following output after successful deletion of the documents.

{ "acknowledged" : true, "deletedCount" : 2 }

This was all about the CRUD operations in MongoDB. It is good to practice it by yourself before moving further.

Share the Post ;)

Related Posts