Skip to content

Instantly share code, notes, and snippets.

@leommoore
Last active October 28, 2016 02:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leommoore/02fec50a429cc76525c8 to your computer and use it in GitHub Desktop.
Save leommoore/02fec50a429cc76525c8 to your computer and use it in GitHub Desktop.
MongoDB - JavaScript

#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();
@RMohan99
Copy link

Thanks

I am beginner. This is quite simple and helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment