Use ObjectId under findOne() to fetch a specific record in MongoDB?


Let us first create a collection with documents −

> db.findOneWorkingDemo.insertOne({"ClientId":1,"ClientName":"Larry","ClientAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7c1716d78f205348bc64d")
}
> db.findOneWorkingDemo.insertOne({"ClientId":2,"ClientName":"Chris","ClientAge":28});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7c17d6d78f205348bc64e")
}
> db.findOneWorkingDemo.insertOne({"ClientId":3,"ClientName":"Robert","ClientAge":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7c1896d78f205348bc64f")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.findOneWorkingDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd7c1716d78f205348bc64d"),
   "ClientId" : 1,
   "ClientName" : "Larry",
   "ClientAge" : 26
}
{
   "_id" : ObjectId("5cd7c17d6d78f205348bc64e"),
   "ClientId" : 2,
   "ClientName" : "Chris",
   "ClientAge" : 28
}
{
   "_id" : ObjectId("5cd7c1896d78f205348bc64f"),
   "ClientId" : 3,
   "ClientName" : "Robert",
   "ClientAge" : 34
}

Following is the query to implement findOne() with ObjectId −

> db.findOneWorkingDemo.findOne({"_id":ObjectId("5cd7c17d6d78f205348bc64e")});

This will produce the following output −

{
   "_id" : ObjectId("5cd7c17d6d78f205348bc64e"),
   "ClientId" : 2,
   "ClientName" : "Chris",
   "ClientAge" : 28
}
raja
Published on 13-Jun-2019 12:16:45
Advertisements