
1. Overview
In this article, we will learn to find documents by id in MongoDB compass. To learn more about MongoDB, refer to these articles.
2. MongoDB ObjectId
In MongoDB, _id field reserved as the primary key for the collection so that we can uniquely identify each document in the collection. The _id field contains a unique ObjectID value.
By default when inserting documents in the collection, MongoDB automatically generates and assigns ObjectId to the _id field of each document. ObjectID can be considered globally unique across all documents.?
You can also specify a 24-character hexadecimal string value explicitly for the ObjectId.
y = ObjectId("507f191e810c19729de860ea") Alternatively, you can specify any other value to the _id field.
3. MongoDB compass find by id
In MongoDB compass, you can use the filter field in UI to find a document by _id field.
3. MongoDB find by id – aggregate pipeline
If you want to filter documents using _id field in the aggregate pipeline, you can use the $match stage.
The?$match?stage filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.
{ $match: { <query> } } $match?takes a document that specifies the query conditions.
You can place the?$match?as early in the aggregation?pipeline?as possible. Because?$match?limits the total number of documents in the aggregation pipeline, earlier?$match?operations minimize the amount of processing down the pipe.
$match has below restrictions:
To include an aggregation expression in?$match, use a?$expr?query expression.
- You cannot use?
$where?in?$match?queries as part of the aggregation pipeline. - You cannot use?
$near?or?$nearSphere?in?$match?queries as part of the aggregation pipeline. - To use?
$text?in the?$match?stage, the?$match?stage has to be the first stage of the pipeline.
4. Conclusion
To sum up, we have learned to find a document by id in MongoDB.