20 C
London
Wednesday, July 23, 2025
HomeSoftware TutorialsMongoDBMongoDB: How to Find Document By id

MongoDB: How to Find Document By id

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories