Eight useful MongoDB queries / by Siobhán Cronin

  1. Number of documents

    db.sf.find().count()

  2. Number of type of thing

    db.sf.find({"type":"node"}).count()

  3. Number of unique things

    db.sf.distinct("created.user").length

  4. Number of things appearing only once

    db.sf.aggregate([{"group":{"_id":"created.user", "count":{"sum":1}}}, {"group":{"_id":"count", "num_users":{"sum":1}}}, {"sort":{"_id":1}}, {"limit":1}])

  5. Find things using a logical AND

    db.sf.find( { "highway": "service", "service": "driveway" } )

  6. Find things using a logical OR

    db.sf.find( {$or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" } ]})

  7. Find and return one document

    db.sf.findOne()

  8. Limit number of rows in find results

    db.sf.find( ... ).limit( )