How to loop through collections with a cursor in MongoDB?

MongoDBDatabaseBig Data Analytics

Following is the syntax to loop through collections with cursor

var anyVariableName1;
var anyVariableName2= db.yourCollectionName.find();
while(yourVariableName2.hasNext()) {
   yourVariableName1= yourVariableName2.next(); printjson(yourVariableName1);
};

Let us create a collection with documents. Following is the query

> db.loopThroughCollectionDemo.insertOne({"StudentName":"John","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ca81f2d6669774125247f")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ca8272d66697741252480")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Chris","StudentAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ca8462d66697741252481")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Robert","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ca8632d66697741252482")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5c9ca81f2d6669774125247f"),
   "StudentName" : "John",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5c9ca8272d66697741252480"),
   "StudentName" : "Larry",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c9ca8462d66697741252481"),
   "StudentName" : "Chris",
   "StudentAge" : 25
}
{
   "_id" : ObjectId("5c9ca8632d66697741252482"),
   "StudentName" : "Robert",
   "StudentAge" : 24
}

Following is the query to loop through collections with cursor

> var allDocumentValue;
> var collectionName=db.loopThroughCollectionDemo.find();
> while(collectionName.hasNext()){allDocumentValue= collectionName.next();printjson(allDocumentValue);
... }

This will produce the following output

{
   "_id" : ObjectId("5c9ca81f2d6669774125247f"),
   "StudentName" : "John",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5c9ca8272d66697741252480"),
   "StudentName" : "Larry",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c9ca8462d66697741252481"),
   "StudentName" : "Chris",
   "StudentAge" : 25
}
{
   "_id" : ObjectId("5c9ca8632d66697741252482"),
   "StudentName" : "Robert",
   "StudentAge" : 24
}
raja
Published on 12-Apr-2019 10:55:10
Advertisements