- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements