How to find through list of ids in MongoDB?


You can use $in operator to find through the list of ids in MongoDB. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.findListOfIdsDemo.insertOne({"StudentName":"Carol","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ecadd2f684a30fbdfd575")
}
> db.findListOfIdsDemo.insertOne({"StudentName":"Bob","StudentAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ecae42f684a30fbdfd576")
}
> db.findListOfIdsDemo.insertOne({"StudentName":"David","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ecaed2f684a30fbdfd577")
}
> db.findListOfIdsDemo.insertOne({"StudentName":"John","StudentAge":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ecaf82f684a30fbdfd578")
}
> db.findListOfIdsDemo.insertOne({"StudentName":"Mike","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ecb092f684a30fbdfd579")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c8ecadd2f684a30fbdfd575"),
   "StudentName" : "Carol",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c8ecae42f684a30fbdfd576"),
   "StudentName" : "Bob",
   "StudentAge" : 25
}
{
   "_id" : ObjectId("5c8ecaed2f684a30fbdfd577"),
   "StudentName" : "David",
   "StudentAge" : 22
}
{
   "_id" : ObjectId("5c8ecaf82f684a30fbdfd578"),
   "StudentName" : "John",
   "StudentAge" : 20
}
{
"_id" : ObjectId("5c8ecb092f684a30fbdfd579"),
"StudentName" : "Mike",
"StudentAge" : 23
}

Here is the query to find through the list of ids −

> var listOfIds = ['5c8ecae42f684a30fbdfd576', '5c8ecaf82f684a30fbdfd578'];
> var documentIds = listOfIds.map(function(myId) { return ObjectId(myId); });
> db.findListOfIdsDemo.find({_id: {$in: documentIds }}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c8ecae42f684a30fbdfd576"),
   "StudentName" : "Bob",
   "StudentAge" : 25
}
{
   "_id" : ObjectId("5c8ecaf82f684a30fbdfd578"),
   "StudentName" : "John",
   "StudentAge" : 20
}

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements