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 find by id
Secondary Sidebar
MongoDB Tutorial
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB JSON
    • MongoDB Careers
    • MongoDB Migration
    • MongoDB Export to Excel
    • 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
    • MongoDB schema
    • MongoDB find by id
    • Mongodb max document size
    • Mongodb not equal
    • MongoDB keyfile
    • MongoDB Hosting
    • MongoDB Kafka Connector
    • MongoDB exists
    • MongoDB express
    • MongoDB Performance
    • MongoDB Connection String
    • MongoDB BI Connector
    • Mongodb aggregation pipeline
    • Mongodb backup and restore
    • MongoDB Drop Collection
    • MongoDB Text Search
    • MongoDB URI
    • MongoDB Full Text Search
    • MongoDB List Databases
    • MongoDB Use Cases
  • 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 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 find by id

MongoDB find by id

Introduction to MongoDB find by id

The following article provides an outline for MongoDB find by id. MongoDB provides a function with the name findById() which is used to retrieve the document matching the ‘id’ as specified by the user. In order to use findById in MongoDB, find() function is used. If no document is found matching the specified ‘id’, it returns null. It is one of the important functions which is used widely when there is a need to retrieve the document according to their ids. Though many languages can use the MongoDB database, in order to perform their database task, it also depends on the language specifications as they vary from each other when it comes to usage of the function.

Syntax of MongoDB find by id

Given below is the basic syntax of using the find by id in a MongoDB database:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

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 (85,992 ratings)

find() function is used in order to use find by id in MongoDB.

db.collection_name.find(query, projection)

Where,

  • query: It is an optional parameter. It specifies the selection filter using the operators of the query. This parameter can be omitted in order to return all the documents in a collection.
  • projection: It is an optional parameter. It specifies the field which will return matching the query filter. This parameter can be omitted in order to return all the fields in the matching documents.

Return type:

It returns the cursor to the documents which match the query criteria.

How does find by id Work in MongoDB?

  • As the name suggests, find by id is used to retrieve the details of the document matching the particular ‘id’ provided by the user where ‘id’ is the automatically generated ‘id’ when a document is created in the database.
  • When the user calls findById(_id) in Mongoose, it automatically calls findOne({_id}) which means that the findById calls findOne in the middle.
  • Casting of queries is done in Mongoose in order to match the schema. ‘Id’ passed by the user is in a string that is converted to ObjectId by Mongoose.
  • The ‘_id’ passed is the automatically generated id when a document is inserted in the database.
  • In order to retrieve the automatically generated id, a simple ‘find()’ function can be used without specifying any criteria.
  • In Mongosh, db.collection_name.find() will automatically iterates the cursor and display upto the first 20 documents of the collection.
  • Different languages use different ways in order to retrieve or find the documents by specifying the id.

Examples of MongoDB find by id

Given below are some of the examples showing the usage of find by id in a MongoDB database. Consider the following conditions:

  • There is a database already present with the name ‘db’.
  • There is a collection in the database with the name ‘myCol’.
  • All the documents are inserted in the collection ‘myCol’ using the insert function.

Example #1

Using the find() function without any parameters.

Code:

db.myCol.find();

Output:

MongoDB find by id 1

Explanation:

  • In the above example, the find() function of MongoDB is used without passing any parameter. Since none of the parameters is passed, find() function will retrieve all the detailed documents present in the collection. We can see that an additional field of ObjectId is automatically inserted at the starting of each document.
  • MongoDB inserts the ObjectId for every new document inserted by the user. This objectId is unique and cannot be the same for two or more documents. It is one of the easiest ways to retrieve the ObjectId of all the documents and use it further according to the specific requirements.

Example #2

Using the find() function and passing the ObjectId parameter in it.

Code:

db.myCol.find({_id : ObjectId("60f532903ded77001064ae92")});

Output:

MongoDB find by id 2

Explanation:

  • In the above example, the document is found on the basis of the ObjectId of the document. ObjectId is the unique id that is automatically allocated when a new document is inserted into the collection.
  • We can provide the ObjectId as a parameter of the find() function in MongoDB and its respective document is displayed on the console to the user.

Example #3

Using the find() function by passing the parameters of the fields other than the unique objectId.

Code:

db.myCol.find({"name" : "sunita"});

Output:

parameters of the fields other than the unique objectId

Explanation:

  • As we can see in the above example, the user can also put the parameter of find function of the other fields of the document.
  • As the “name” is also a field on which each document can be filtered, so the document having the “name” as “sunita” is found and all its details are displayed to the user on the console.

Suppose there are two or more documents in the collections having the same value for the particular field.bLet see the situation with the help of the data present in the collection similar to the one given below:

Code:

db.myCol.find();

Output:

MongoDB find by id 4

Example #4

Using the find() function and passing the parameter of the field which is the same for more than one record.

Code:

db.myCol.find({"city" :"agra"});

Output:

which is the same for more than one record

Explanation:

  • In the above example, as we can see that there is more than one document present in the collection having the field “city” as “agra”. So when we pass the parameter of “city” : “agra”, all the documents matching the criteria will be displayed to the user on the console. It is never the case of find() function that only one record will be retrieved at a time.
  • In the case of ObjectId only one document would be displayed to the user as it is unique to each document and can never be the same. Else for the other cases, all the documents satisfying the condition mentioned in the find() parameters would be displayed to the user on the console.

Conclusion

The above description clearly explains what the find by id is and how it works in MongoDB to retrieve the documents according to the specified id by the user. As we know that the find() function is used in order to perform the task of retrieving the documents with the given id. The find() function internally calls the findOne() in order to handle the situation accordingly.

Recommended Articles

This is a guide to MongoDB find by id. Here we discuss the introduction, how does find by id work in MongoDB? and their examples respectively. You may also have a look at the following articles to learn more –

  1. MongoDB Join
  2. MongoDB findOne()
  3. MongoDB Date Query
  4. MongoDB Database
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

Special Offer - MongoDB Training Program (4 Courses, 2 Projects) Learn More