Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Display MongoDB records by ObjectId?
Let us first create a collection with documents −
> db.findByObjectIdDemo.insertOne({"ClientName":"Larry","ClientAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd68cd657806ebf1256f11a")
}
> db.findByObjectIdDemo.insertOne({"ClientName":"Chris","ClientAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd68cdc57806ebf1256f11b")
}
> db.findByObjectIdDemo.insertOne({"ClientName":"David","ClientAge":38,"isMarried":true});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd68cf657806ebf1256f11c")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.findByObjectIdDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd68cd657806ebf1256f11a"),
"ClientName" : "Larry",
"ClientAge" : 23
}
{
"_id" : ObjectId("5cd68cdc57806ebf1256f11b"),
"ClientName" : "Chris",
"ClientAge" : 26
}
{
"_id" : ObjectId("5cd68cf657806ebf1256f11c"),
"ClientName" : "David",
"ClientAge" : 38,
"isMarried" : true
}
Following is the query to find by ObjectId −
> db.findByObjectIdDemo.find({_id: new ObjectId("5cd68cf657806ebf1256f11c")}).toArray(function(err, myDocument) { console.log(myDocument); });
This will produce the following output −
[
{
"_id" : ObjectId("5cd68cf657806ebf1256f11c"),
"ClientName" : "David",
"ClientAge" : 38,
"isMarried" : true
}
]Advertisements