How to Insert, Update, Delete and Query Document in MongoDB Collection

Last updated on May 30 2022
Satyen Sahu

Table of Contents

How to Insert, Update, Delete and Query Document in MongoDB Collection

In this blog , we’ll learn how to insert , update , delete and query document in MongoDB collection.

MongoDB – Insert Document

The insert() Method

To insert data into MongoDB collection, you would like to use MongoDB’s insert() or save() method.
Syntax
The basic syntax of insert() command is as follows −
>db.COLLECTION_NAME.insert(document)
Example
>db.mycol.insert({
_id: ObjectId(7df78ad8902c),
title: ‘MongoDB Overview’,
description: ‘MongoDB is no sql database’,
by: ‘tecklearn’,
url: ‘http://www.tecklearn.com’,
tags: [‘mongodb’, ‘database’, ‘NoSQL’],
likes: 100
})
Here mycol is our collection name, as created within the previous chapter. If the collection doesn’t exist within the database, then MongoDB will create this collection and then insert a document into it.
In the inserted document, if we don’t specify the _id parameter, then MongoDB assigns a unique ObjectId for this document.
_id is 12 bytes hexadecimal number unique for every document within a collection. 12 bytes are divided as follows −
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id,
3 bytes incrementer)
To insert multiple documents in a single query, you can pass an array of documents in insert() command.
Example
>db.post.insert([
{
title: ‘MongoDB Overview’,
description: ‘MongoDB is no sql database’,
by: ‘tecklearn’,
url: ‘http://www.tecklearn.com’,
tags: [‘mongodb’, ‘database’, ‘NoSQL’],
likes: 100
},

{
title: ‘NoSQL Database’,
description: “NoSQL database doesn’t have tables”,
by: ‘tecklearn’,
url: ‘http://www.tecklearn.com’,
tags: [‘mongodb’, ‘database’, ‘NoSQL’],
likes: 20,
comments: [
{
user:’user1′,
message: ‘My first comment’,
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])
To insert the document you can use db.post.save(document) also. If you don’t specify _id within the document then save() method will work same as insert() method. If you specify _id then it will replace whole data of document containing _id as specified in save() method.

MongoDB – Query Document

In this section, we’ll learn how to insert document within MongoDB collection.

The find() Method

To query data from MongoDB collection, you need to use MongoDB’s find() method.
Syntax
The basic syntax of find() method is as follows −
>db.COLLECTION_NAME.find()
find() method will display all the documents in a non-structured way.

The pretty() Method

To display the leads to a formatted way, you’ll use pretty() method.
Syntax
>db.mycol.find().pretty()
Example
>db.mycol.find().pretty()
{
“_id”: ObjectId(7df78ad8902c),
“title”: “MongoDB Overview”,
“description”: “MongoDB is no sql database”,
“by”: “tecklearn”,
“url”: “http://www.tecklearn.com”,
“tags”: [“mongodb”, “database”, “NoSQL”],
“likes”: “100”
}
>
Apart from find() method, there is findOne() method, that returns just one document.

RDBMS Where Clause Equivalents in MongoDB

To query the document on the basis of some condition, you can use subsequent operations.

Operation Syntax Example RDBMS Equivalent
Equality {<key>:<value>} db.mycol.find({“by”:”tecklearn”}).pretty() where by = ‘tecklearn’
Less Than {<key>:{$lt:<value>}} db.mycol.find({“likes”:{$lt:50}}).pretty() where likes < 50
Less Than Equals {<key>:{$lte:<value>}} db.mycol.find({“likes”:{$lte:50}}).pretty() where likes <= 50
Greater Than {<key>:{$gt:<value>}} db.mycol.find({“likes”:{$gt:50}}).pretty() where likes > 50
Greater Than Equals {<key>:{$gte:<value>}} db.mycol.find({“likes”:{$gte:50}}).pretty() where likes >= 50
Not Equals {<key>:{$ne:<value>}} db.mycol.find({“likes”:{$ne:50}}).pretty() where likes != 50

AND in MongoDB
Syntax
In the find() method, if you pass multiple keys by separating them by ‘,’ then MongoDB treats it as AND condition. Subsequent is that the basic syntax of AND −
>db.mycol.find(
{
$and: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will show all the tutorials written by ‘tecklearn’ and whose title is ‘MongoDB Overview’.
>db.mycol.find({$and:[{“by”:”tecklearn”},{“title”: “MongoDB Overview”}]}).pretty() {
“_id”: ObjectId(7df78ad8902c),
“title”: “MongoDB Overview”,
“description”: “MongoDB is no sql database”,
“by”: “tecklearn”,
“url”: “http://www.tecklearn.com”,
“tags”: [“mongodb”, “database”, “NoSQL”],
“likes”: “100”
}
For the above given example, equivalent where clause will be ‘ where by = ‘tecklearn’ AND title = ‘MongoDB Overview’ ‘. You can pass any number of key, value pairs in find clause.
OR in MongoDB
Syntax
To query documents based on the OR condition, you need to use $or keyword. Following is the basic syntax of OR −
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will show all the tutorials written by ‘tecklearn’ or whose title is ‘MongoDB Overview’.
>db.mycol.find({$or:[{“by”:”tecklearn”},{“title”: “MongoDB Overview”}]}).pretty()
{
“_id”: ObjectId(7df78ad8902c),
“title”: “MongoDB Overview”,
“description”: “MongoDB is no sql database”,
“by”: “tecklearn”,
“url”: “http://www.tecklearn.com”,
“tags”: [“mongodb”, “database”, “NoSQL”],
“likes”: “100”
}
>
Using AND and OR Together
Example
The subsequent example will show the documents that have likes greater than 10 and whose title is either ‘MongoDB Overview’ or by is ‘tecklearn’. Equivalent SQL where clause is ‘where likes>10 AND (by = ‘tecklearn’ OR title = ‘MongoDB Overview’)’
>db.mycol.find({“likes”: {$gt:10}, $or: [{“by”: “tecklearn”},
{“title”: “MongoDB Overview”}]}).pretty()
{
“_id”: ObjectId(7df78ad8902c),
“title”: “MongoDB Overview”,
“description”: “MongoDB is no sql database”,
“by”: “tecklearn”,
“url”: “http://www.tecklearn.com”,
“tags”: [“mongodb”, “database”, “NoSQL”],
“likes”: “100”
}
>

MongoDB – Update Document

MongoDB’s update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.

MongoDB Update() Method

The update() method updates the values in the existing document.
Syntax
The basic syntax of update() method is as follows −
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Example
Consider the mycol collection has the subsequent data.
{ “_id” : ObjectId(5983548781331adf45ec5), “title”:”MongoDB Overview”}
{ “_id” : ObjectId(5983548781331adf45ec6), “title”:”NoSQL Overview”}
{ “_id” : ObjectId(5983548781331adf45ec7), “title”:”Tecklearn Overview”}
Following example will set the new title ‘New MongoDB Tutorial’ of the documents whose title is ‘MongoDB Overview’.
>db.mycol.update({‘title’:’MongoDB Overview’},{$set:{‘title’:’New MongoDB Tutorial’}})
>db.mycol.find()
{ “_id” : ObjectId(5983548781331adf45ec5), “title”:”New MongoDB Tutorial”}
{ “_id” : ObjectId(5983548781331adf45ec6), “title”:”NoSQL Overview”}
{ “_id” : ObjectId(5983548781331adf45ec7), “title”:”Tecklearn Overview”}
>
By default, MongoDB will update only a single document. To update multiple documents, you need to set a parameter ‘multi’ to true.
>db.mycol.update({‘title’:’MongoDB Overview’},
{$set:{‘title’:’New MongoDB Tutorial’}},{multi:true})

MongoDB Save() Method

The save() method replaces the prevailing document with the new document passed within the save() method.
Syntax
The basic syntax of MongoDB save() method is shown below −
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Example
Subsequent example will replace the document with the _id ‘5983548781331adf45ec5’.
>db.mycol.save(
{
“_id” : ObjectId(5983548781331adf45ec5), “title”:”Tecklearn New Topic”,
“by”:”Tecklearn”
}
)
>db.mycol.find()
{ “_id” : ObjectId(5983548781331adf45ec5), “title”:”Tecklearn New Topic”,
“by”:”Tecklearn”}
{ “_id” : ObjectId(5983548781331adf45ec6), “title”:”NoSQL Overview”}
{ “_id” : ObjectId(5983548781331adf45ec7), “title”:”Tecklearn Overview”}
>

MongoDB – Delete Document

In this section, we’ll learn how to delete a document using MongoDB.

The remove() Method

MongoDB’s remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
• deletion criteria − (Optional) deletion criteria according to documents will be removed.
• justOne − (Optional) if set to true or 1, then remove only one document.
Syntax
Basic syntax of remove() method is as follows −
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example
Consider the mycol collection has the subsequent data.
{ “_id” : ObjectId(5983548781331adf45ec5), “title”:”MongoDB Overview”}
{ “_id” : ObjectId(5983548781331adf45ec6), “title”:”NoSQL Overview”}
{ “_id” : ObjectId(5983548781331adf45ec7), “title”:”Tecklearn Overview”}
Following example will remove all the documents whose title is ‘MongoDB Overview’.
>db.mycol.remove({‘title’:’MongoDB Overview’})
>db.mycol.find()
{ “_id” : ObjectId(5983548781331adf45ec6), “title”:”NoSQL Overview”}
{ “_id” : ObjectId(5983548781331adf45ec7), “title”:”Tecklearn Overview”}
>

Remove Only One

If there are multiple records and you want to delete only the first record, then set justOne parameter in remove() method.
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Remove All Documents

If you don’t specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL’s truncate command.
>db.mycol.remove({})
>db.mycol.find()
>

So, this brings us to the end of blog. This Tecklearn ‘How to Insert , Update , Delete and Query Document in MongoDB Collection’ helps you with commonly asked questions if you are looking out for a job in MongoDB and No-SQL Database Domain.
If you wish to learn and build a career in MongoDB or No-SQL Database domain, then check out our interactive, MongoDB Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

MongoDB Training

MongoDB Training

About the Course

Tecklearn’s MongoDB Training helps you to master the NoSQL database. The course makes you job-ready by letting you comprehend schema design, data modelling, replication, and query with MongoDB through real-time examples. Along with this, you’ll also gain hands-on expertise in installing, configuring, and maintaining the MongoDB environment, including monitoring and operational strategies from this online MongoDB training. Upon completion of this online training, you will hold a solid understanding and hands-on experience with MongoDB.

Why Should you take MongoDB Training?

• MongoDB – a $36 billion to a $40 billion market growing at 8% to 9% annually – Forbes.com
• Average salary of a Mongo DB certified professional is $134k – Indeed.com
• MongoDB has more than 900 customers, including 27 Fortune 100 companies like Cisco, eBay, eHarmony, MetLife & Salesforce.com

What you will Learn in this Course?

Introduction to MongoDB and Importance of NoSQL
• Understanding the basic concepts of RDBMS
• What is NoSQL Database and its significance?
• Challenges of RDBMS and How NoSQL suits Big Data needs
• Types of NoSQL Database and NoSQL vs. SQL Comparison
• CAP Theorem and Implementing NoSQL
• Introduction to MongoDB and its advantages
• Design Goals for MongoDB Server and Database, MongoDB tools
• Collection, Documents and Key Value Pair
• Introduction to JSON and BSON documents
• MongoDB installation
MongoDB Installation
• MongoDB Installation
• Basic MongoDB commands and operations,
• Mongo Chef (MongoGUI) Installation
Schema Design and Data Modelling
• Why Data Modelling?
• Data Modelling Approach
• Data Modelling Concepts
• Difference between MongoDB and RDBMS modelling
• Challenges for Data Modelling
• Model Relationships between Documents
• Data Model Examples and Patterns
• Model Tree Structures
CRUD Operations
• MongoDB Architecture
• CRUD Introduction and MongoDB CRUD Concepts
• MongoDB CRUD Concerns (Read and Write Operations)
• Cursor Query Optimizations and Query Behaviour in MongoDB
• Distributed Read and Write Queries
• MongoDB Datatypes
Indexing and Aggregation Framework
• Concepts of Data aggregation and types and data indexing concepts
• Introduction to Aggregation
• Approach to Aggregation
• Types of Aggregation: Pipeline, MapReduce and Single Purpose
• Performance Tuning
MongoDB Administration
• Administration concepts in MongoDB
• MongoDB Administration activities: Health check, recovery, backup, database sharing and profiling, performance tuning etc.
• Backup and Recovery Methods for MongoDB
• Export and Import of Data from MongoDB
• Run time configuration of MongoDB
MongoDB Security
• Security Introduction
• MongoDB security Concepts and security approach
• MongoDB integration with Java and Robomongo
Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "How to Insert, Update, Delete and Query Document in MongoDB Collection"

Leave a Message

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