Retrieving specific documents from collection by _id in MongoDB


To retrieve document from collection by _id, use find() with $in. Let us create a collection with documents −

> db.demo281.insertOne({"Name":"Chris","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4aac28dd099650a5401a66")
}
> db.demo281.insertOne({"Name":"Bob","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4aac46dd099650a5401a67")
}
> db.demo281.insertOne({"Name":"David","Age":28});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4aac4fdd099650a5401a68")
}

Display all documents from a collection with the help of find() method −

> db.demo281.find();

This will produce the following output −

{ "_id" : ObjectId("5e4aac28dd099650a5401a66"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e4aac46dd099650a5401a67"), "Name" : "Bob", "Age" : 23 }
{ "_id" : ObjectId("5e4aac4fdd099650a5401a68"), "Name" : "David", "Age" : 28 }

Following is the query to retrieve specific documents from collection by _id −

>db.demo281.find({_id:{$in:[ObjectId("5e4aac28dd099650a5401a66"),ObjectId("5e4aac46dd099650a5401a67")]}});

This will produce the following output −

{ "_id" : ObjectId("5e4aac28dd099650a5401a66"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e4aac46dd099650a5401a67"), "Name" : "Bob", "Age" : 23 }

Updated on: 31-Mar-2020

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements