Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to count a cursor's iteration in MongoDB?
To count a cursor's iteration in MongoDB, you need to use custom logic with a while loop along with a find() cursor. This allows you to iterate through documents and count specific conditions during traversal.
Syntax
var cursor = db.collection.find();
var count = 0;
while (cursor.hasNext()) {
var document = cursor.next();
// Apply your counting logic here
if (condition) {
count++;
}
}
Sample Data
db.demo724.insertMany([
{
details: {
id: 101,
otherDetails: [
{ Name: "Chris" }
]
}
},
{
// Empty document
},
{
details: {
id: 1001
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5eab0cce43417811278f5890"),
ObjectId("5eab0cce43417811278f5891"),
ObjectId("5eab0cce43417811278f5892")
]
}
Display all documents from the collection ?
db.demo724.find();
{ "_id": ObjectId("5eab0cce43417811278f5890"), "details": { "id": 101, "otherDetails": [ { "Name": "Chris" } ] } }
{ "_id": ObjectId("5eab0cce43417811278f5891") }
{ "_id": ObjectId("5eab0cce43417811278f5892"), "details": { "id": 1001 } }
Example: Count Documents with "details" Field
var c = db.demo724.find();
var detailsCount = 0;
while (c.hasNext()) {
var current = c.next();
if (typeof current["details"] != "undefined") {
detailsCount++;
}
}
print("Number of details: " + detailsCount);
Number of details: 2
How It Works
-
hasNext()checks if more documents exist in the cursor -
next()retrieves the current document and advances the cursor - Custom condition logic determines when to increment the counter
- The loop continues until all documents are processed
Conclusion
Use cursor iteration with while loops to implement custom counting logic in MongoDB. This approach gives you full control over which documents to count based on specific field conditions or complex criteria.
Advertisements
