Get the array of _id in MongoDB?


The _id in MongoDB is a field, which is mandatory. In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. Following is the syntax to get the array of all the ids i.e. _id in MongoDB

db.yourCollectionName.find({ _id : { $in : [yourValue1,yourValue2,yourValue3,.......N] } } );

Let us first implement the following query to create a collection with documents

> db.selectInWhereIdDemo.insertOne({"_id":23});
{ "acknowledged" : true, "insertedId" : 23 }
> db.selectInWhereIdDemo.insertOne({"_id":28});
{ "acknowledged" : true, "insertedId" : 28 }
> db.selectInWhereIdDemo.insertOne({"_id":45});
{ "acknowledged" : true, "insertedId" : 45 }
> db.selectInWhereIdDemo.insertOne({"_id":75});
{ "acknowledged" : true, "insertedId" : 75 }
> db.selectInWhereIdDemo.insertOne({"_id":85});
{ "acknowledged" : true, "insertedId" : 85 }
> db.selectInWhereIdDemo.insertOne({"_id":145});
{ "acknowledged" : true, "insertedId" : 145 }

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

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

This will produce the following output

{ "_id" : 23 }
{ "_id" : 28 }
{ "_id" : 45 }
{ "_id" : 75 }
{ "_id" : 85 }
{ "_id" : 145 }

Following is the query to get _id i.e. all the ids in an array

> db.selectInWhereIdDemo.find({ _id : { $in : [23,45,85,145] } } );

This will produce the following output

{ "_id" : 23 }
{ "_id" : 45 }
{ "_id" : 85 }
{ "_id" : 145 }

Updated on: 30-Jul-2019

636 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements