When messing around with the Mongo console I’ve found that Mongo is not just JavaScript, and the JS-foo and standard APIs you might be used to in the browser or in Node are not always available – where’s console.log, for Console’s sake?
Here’s a head start on how to perform some basic manipulations, assuming prior familiarity with JavaScript and Mongo themselves.
So suppose:
- You’ve got your data spread around mutiple collections (supposed they’re named ’employees1′, ’employees1′, ’employees1′),
- You want to query all the fields of a nested document (say, the field ‘city’ of nested document ‘address’, which not all the users have).
You might want something like this:
mongo > res = [];
mongo > for(i=0;i<4;i++){ res=res.concat(db.getCollection('coll'+i).find({"address": {$exists: true}}).toArray()); }
mongo > res.length //number of employees that have an 'address' sub-document.
mongo > res.forEach(function(x){print(x.address.city)}) //print out all the cities
Hooray for science.