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.
Additional Resources
The following tutorials explain how to perform other common operations in MongoDB:
MongoDB: How to Add a New Field in a Collection
MongoDB: How to Group By and Count
MongoDB: How to Group By Multiple Fields