Table of Contents
MongoDB is a NoSQL database that provides the ability to store data in a more flexible way than traditional RDBMS. Finding documents by id is an important task that can be done in MongoDB using the find() method. This method takes a document query as an argument and returns all matching documents from the collection. To find a document by id, pass a filter object with the _id field set to the document’s id value. Additionally, the findOne() method can also be used to return a single document matching the given query.
You can use the following basic syntax to find a document by id in MongoDB:
db.collection.find(ObjectId('619527e467d6742f66749b72'))
The following examples show how to use this syntax with a collection teams with the following documents:
{ _id: ObjectId("619527e467d6742f66749b70"), team: 'Rockets', position: 'Center', points: 19 } { _id: ObjectId("619527e467d6742f66749b71"), team: 'Rockets', position: 'Forward', points: 26 } { _id: ObjectId("619527e467d6742f66749b72"), team: 'Cavs', position: 'Guard', points: 33 }
Example: Find Document by id
We can use the following code to find the document with a specific id in the teams collection:
db.teams.find(ObjectId('619527e467d6742f66749b72'))
This query returns the following document:
{ _id: ObjectId("619527e467d6742f66749b72"), team: 'Cavs', position: 'Guard', points: 33 }
We can change the id to find another document with a different id in the teams collection:
db.teams.find(ObjectId('619527e467d6742f66749b71'))
This query returns the following document:
{ _id: ObjectId("619527e467d6742f66749b71"), team: 'Rockets', position: 'Forward', points: 26 }
Note that if you query for a certain document with an id that doesn’t exist, no results will be returned.
The following tutorials explain how to perform other common operations in MongoDB: