Iterate a cursor and print a document in MongoDB?


For this, use printjson. Let us first create a collection with documents −

> db.cursorDemo.insertOne({"StudentFullName":"John Smith","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7f0d08f9e6ff3eb0ce442")
}
> db.cursorDemo.insertOne({"StudentFullName":"John Doe","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7f0df8f9e6ff3eb0ce443")
}
> db.cursorDemo.insertOne({"StudentFullName":"Carol Taylor","StudentAge":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444")
}
> db.cursorDemo.insertOne({"StudentFullName":"Chris Brown","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7f0f88f9e6ff3eb0ce445")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cc7f0d08f9e6ff3eb0ce442"),
   "StudentFullName" : "John Smith",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5cc7f0df8f9e6ff3eb0ce443"),
   "StudentFullName" : "John Doe",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444"),
   "StudentFullName" : "Carol Taylor",
   "StudentAge" : 20
}
{
   "_id" : ObjectId("5cc7f0f88f9e6ff3eb0ce445"),
   "StudentFullName" : "Chris Brown",
   "StudentAge" : 24
}

Following is the query to iterate and print document with printjson −

> db.cursorDemo.find().forEach(printjson);

This will produce the following output −

{
   "_id" : ObjectId("5cc7f0d08f9e6ff3eb0ce442"),
   "StudentFullName" : "John Smith",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5cc7f0df8f9e6ff3eb0ce443"),
   "StudentFullName" : "John Doe",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444"),
   "StudentFullName" : "Carol Taylor",
   "StudentAge" : 20
}
{
   "_id" : ObjectId("5cc7f0f88f9e6ff3eb0ce445"),
   "StudentFullName" : "Chris Brown",
   "StudentAge" : 24
}

Following is the second query if we want the specific fields only like the fields “StudentFullName” and “StudentAge” −

> db.cursorDemo.find({}, { "StudentFullName": 1,"StudentAge":1, "_id": 0 }).forEach(printjson)

This will produce the following output −

{ "StudentFullName" : "John Smith", "StudentAge" : 23 }
{ "StudentFullName" : "John Doe", "StudentAge" : 21 }
{ "StudentFullName" : "Carol Taylor", "StudentAge" : 20 }
{ "StudentFullName" : "Chris Brown", "StudentAge" : 24 }

Updated on: 30-Jul-2019

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements