Retrieving specific documents from collection by _id in MongoDB

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 31-Mar-2020 16:54:34
Advertisements