#MongoDB - JavaScript
Since a query may return a large number of records which is too large for the client, the find
returns a cursor instead of the data. This cursor can be assigned to a variable.
var vendorCursor = db.vendors.find();
You can see the size of the cursor using:
vendorCursor.size();
You can check to see if there is more data after the current cursor point in the data set using:
vendorCursor.hasNext();
##Iterating through the cursor
forEach
can then be used to iterate through the data. The example below iterates through a set and prints the vendorName and a count at the end.
function vendorCount() {
var vendorCursor = db.vendors.find();
var count = 0;
vendorCursor.forEach(function(myDoc) {
print("vendor: " + myDoc.vendorName)
count++
});
print("\nVendor Count: " + count);
}
var recordCount = function() {
var userCount = db.users.count();
var locationCount = db.locations.count();
var cityCount = db.cities.count();
var productCount = db.products.count();
var entry = {
_id: Date(),
userCount: userCount,
locationCount: locationCount,
cityCount: cityCount,
productCount: productCount
}
db.Stats.save(entry);
print("\nToday's User Count: " + entry.userCount);
print("\nToday's Location Count: " + entry.locationCount);
print("\nToday's City Count: " + entry.cityCount);
print("\nToday's Product Count: " + entry.productCount);
}
recordCount();
Thanks
I am beginner. This is quite simple and helpful.