EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MongoDB Tutorial MongoDB Collection
Secondary Sidebar
MongoDB Tutorial
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Delete Collection
    • Mongodb show collections
    • MongoDB Auto Increment
    • MongoDB Triggers
    • MongoDB Projection
    • Replication in MongoDB
    • MongoDB Database
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB MapReduce
    • MongoDB Geospatial
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
    • MongoDB Join Two Collections
    • MongoDB Group by Multiple Fields
    • MongoDB Pagination
    • MongoDB Replica Set
    • MongoDB Bulk Update
    • MongoDB greater than
    • MongoDB Encryption
    • MongoDB find in array
    • MongoDB like query
    • Mongodb shell
    • MongoDB port
    • MongoDB Query Operators
    • MongoDB Web Interface
    • MongoDB Query Array
    • MongoDB Transactions
    • MongoDB Not In
    • MongoDB not null
    • MongoDB npm
    • MongoDB Remove
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB Data Types
    • MongoDB Administration
    • Data Modeling in MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Commands
    • Mongodb updateMany
    • MongoDB Aggregation
    • Mongodb unwind
    • Mongodb where
    • MongoDB BSON
    • MongoDB Filter
    • Mongodb Match
    • MongoDB sort by date
    • MongoDB Limit()
    • MongoDB Atlas Login
    • MongoDB Relational Database
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB findOne()
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB findAndModify
    • Mongodb findOneAndUpdate
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join

Related Courses

MongoDB Certification Course

Oracle Certification Course

All in One Data Science Course

SQL Training Course

Oracle DBA Course

MS SQL Certification Course

MongoDB Collection

By Priya PedamkarPriya Pedamkar

MongoDB Collection

Introduction to MongoDB Collection

We have a table in the relational database management system. In MongoDB, we have a collection to store N number of records that are documented. Collection stores N number of documents. MongoDB accepts unstructured data. Document stores data which is not in structure format because MongoDB is a schema-less database. We don’t need to define column and datatype while creating a collection. Collection name starts with name or namespace, and it can have any numbers. The collection name should not exceed 128 characters. By using (.), the collection gets organized into groups. We can create any number of collections in the database. We should first create a database to store the collection value.

How does Collection Methods work in MongoDB?

1. We first need a MongoDB database to create a collection.

USE<"database name">

2. Mention Collection name and insert a record into it.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

collection_name.create(<document>)

3. Collection Gets Created.

4. We can view any number of collections with command.

show collections

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,471 ratings)

Syntax

1. To create a collection

db.collection_name(field:value)

2. To delete collection

collection_name.drop()

Examples to Implement MongoDB Collection

Below are the examples of implementing MongoDB Collection:

A) Create a Collection

1. We have created a database named hospital.

Code:

use hospital

Output:

MongoDB Collection - 1

2. We have created a collection named the patient.

Code:

db.patient.insert({})

Output:

MongoDB Collection - 2

  • If we don’t enter any value inside (), then an error will appear. Error: no object passed to insert!

3. We have inserted a record for the patient with field: value pair.

Code:

db.patient.insert({name:'akash',age:23,reason:'fever'})

  • Be careful while creating record because if we don’t use ( ‘ ‘) for the string, then an error will appear.

MongoDB Collection - 3

  • “nInserted”:1 means record inserted successfully.

4. To show the list of collections.

Code:

show collections

Output:

MongoDB Collection - 4

5. We have inserted multiple records into the patient collection.

Code:

db.patient.insert({name:'megha',age:24,reason:'fever'},{name:'rohit',age:25,reason:'cuff'})

Output:

MongoDB Collection - 5

6. We have inserted the record into the patient history.

Code:

db.patienthistory.insert({name:'rupali',age:34,experience:12})

Output:

MongoDB Collection - 6

B) Delete Collection (drop the collection)

We can delete the collection from the database. Select the database from which you want to delete the collection.

  • USE <database name>
  • Verify if the collection is present or not with <show collections>.
  • Apply drop command with a collection.

1. We have used the hospital database.

Code:

use hospital

Output:

USE

Code:

db.patienthistory.drop()

Output:

MongoDB Collection - 8

  • We get the true message which means collection deleted successfully.
  • If the false message is displayed, then the collection is not deleted yet.

2. We have checked the collection list. We can observe that patient history is not present.

Code:

show collections

Output:

show collection

3. If we try to delete the non-existing collection, then the false message is displayed.

Code:

db.library.drop()

Output:

MongoDB Collection - 10

1. Find ()

1. This command will display data from collection means documents/records inserted into the collection.

Syntax:

db.collection_name.find()

Code:

db.patient.find()

  • _id – it is defined for each document by default if we do not mention it while creating a document.
  • We have inserted name, age and reason for each patient.
  • We can observe that no data is present in the first record because we have created a document without field: value pair.

Output:

Find ()

2. We have created a document with a collection with no record.

Syntax:

collection_name.insert({})

Code:

db.injection.insert({})

Output:

Find ()

2. Filtering collection

If we have a huge dataset and want to find a particular value or fetch certain records, then find () will help us.

Syntax:

db.collection_name.find({field:value})

Code:

db.patient.find({name:"akash"})

Output: It has fetched all the details of Akash from the patient collection.

Filtering collection

3. Formatting the result

We can observe in the above image, and filtering has displayed the result in one single line. The above-displayed document has less field: value pair, so it is easy to read, but if the document contains the huge number of the field: value pair, then it isn’t easy to read. We can format the result that is fetched document will be displayed in vertical format.

Syntax:

db.collection_name.find({field:value}).pretty()

Code:

db.patient.find({name:"akash"}).pretty()

Output:

Formatting the result

4. OR condition

This command will fetch a record from two or more conditions. Suppose we have mentioned two conditions then if one condition is not satisfied, then the second condition will check and the result gets displayed.

Syntax:

db.collection_name.({$or:[{field:value},{field:{$lt:value}}]})

Code:

db.patient.find({ $or:[{reason:"cuff"},{age:{$lt:23}}]})

Output:

OR condition

$lt means age is less than 23. From the above image, we can understand that there are two conditions. One reason is cough and age is less than 23. This command has checked for the reason as a cuff, but it did not find age less than 23. So only one condition is matched, and the result is displayed.

  • In the result section, we can see reason as the cough is displayed even if age is not less than 23.
  • We have fetched results with the pretty() command, now it is easy to understand for us while reading it.

Code:

db.patient.find({ $or:[{reason:"cuff"},{age:{$lt:23}}]}).pretty()

Output:

MongoDB Collection - 16

5. AND condition

1. One or more conditions should be matched.

Syntax:

db.collection_name.find({field:value,field:{value}})

Code:

db.patient.find({reason:"cuff",age:{$lt:23}})

Output:

AND condition

2. We can observe in the above image no result is displayed because one condition is false. The first condition is a cough, and the second condition is age less than 23. In the above example, the second condition failed, and we get no result.

We are going to change the command. We will change the age of <40.

Code:

db.patient.find({reason:"cuff",age:{$lt:40}})

Output:

MongoDB Collection - 18

We can observe in the above image, and the result is displayed because reason as cuff and age <40 conditions are matched.

6. findOne()

It will display the first record by default.

Syntax:

collection_name.findOne()

Code:

db.patient.findOne()

Output: The result shows _id only because we have not inserted any field: value while creating a document.

findOne()

Output: If we run this command N number of times, the same result will appear.

findOne()

7. _id

If we do not assign any value to an id, then the system generates id automatically. If we assign value to id while creating the record, then id will be displayed when we fetch the result.

Syntax:

db.collection_name.insert({_id:1,field:value,field:value,…})

Code:

db.patient.insert({_id:1,name:"dhruvi",age:26,reason:"cough"})

Output:

_id

Code:

db.patient.find()

Output:

_id

Conclusion

We have learned about the collection, database, and document in MongoDB. Syntax of collection, database, and document. To create a database “USE” command should be used when we create a collection inside the database, and the document gets created inside the collection. We can perform addition, deletion, and updating of documents inside the collection. Information about the database is presented in certain collections, and it is grouped in system namespace as (dbname.system.*).

Recommended Articles

This is a guide to MongoDB Collection. Here we discuss basic concept, methods, and examples of MongoDB collections with proper codes and outputs. You can also go through our other related articles to learn more –

  1. MongoDB List Collections
  2. MongoDB Tools
  3. How to Works MongoDB Limit()?
  4. Guide to MongoDB MapReduce
  5. MongoDB Data Types | Examples
  6. Guide to MongoDB Geospatial
Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)
  4 Online Courses |  2 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (14 Courses, 8+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
SQL Training Program (7 Courses, 8+ Projects)4.7
Oracle DBA Database Management System Training (2 Courses)4.7
MS SQL Training (16 Courses, 11+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more