How to count a cursor’s iteration in MongoDB?


You need to use custom logic with the help of while loop along with find() cursor. Let us create a collection with documents −

> db.demo724.insertOne(
...    {
...       details:
...       {
...          id:101,
...          otherDetails:[
...             {Name:"Chris"}
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab0cce43417811278f5890")
}
>
>
> db.demo724.insertOne(
... {
...
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab0cce43417811278f5891")
}
> db.demo724.insertOne(
...    {
...       details:
...       {
...          id:1001
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab0cce43417811278f5892")
}

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

> db.demo724.find();

This will produce the following output &miinus;

{ "_id" : ObjectId("5eab0cce43417811278f5890"), "details" : { "id" : 101, "otherDetails" : [ { "Name" : "Chris" } ] } }
{ "_id" : ObjectId("5eab0cce43417811278f5891") }
{ "_id" : ObjectId("5eab0cce43417811278f5892"), "details" : { "id" : 1001 } }

Following is the query to count a cursor’s iteration in MongoDB −

> var c=db.demo724.find();
> var detailsCount=0;
> while (c.hasNext()) {
...    var current = c.next();
...    if (typeof current["details"] != "undefined") {
...       detailsCount++;
...    }
... }
1
> print("number of details: " + detailsCount);

This will produce the following output −

number of details: 2

Updated on: 15-May-2020

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements