Fetch all the ids of MongoDB documents?

MongoDBDatabaseBig Data Analytics

To fetch all the ids, simply use find() in MongoDB. Let us create a collection with documents −

> db.demo169.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e36975e9e4f06af551997d7")
}
> db.demo169.insertOne({"StudentName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3697629e4f06af551997d8")
}
> db.demo169.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3697679e4f06af551997d9")
}

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

> db.demo169.find();

This will produce the following output −

{ "_id" : ObjectId("5e36975e9e4f06af551997d7"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e3697629e4f06af551997d8"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e3697679e4f06af551997d9"), "StudentName" : "David" }

Following is the query to get document ids of all the MongoDB documents in a collection −

> var iterator=db.demo169.find({},{"StudentName":0});

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

> iterator;

This will produce the following output −

{ "_id" : ObjectId("5e36975e9e4f06af551997d7") }
{ "_id" : ObjectId("5e3697629e4f06af551997d8") }
{ "_id" : ObjectId("5e3697679e4f06af551997d9") }
raja
Published on 01-Apr-2020 12:04:00
Advertisements