Cogs and Levers A blog full of technical stuff

MongoDB console cheatsheet

Basic retrieves

Find all items in a collection

	db.collection.find();

Count all items in a collection

	db.collection.count();

Find all items in a collection with criteria (Mongo operators reference)

	db.collection.find({"field": value});

Reduce the field-set returned by a query

	db.collection.find({}, {"field": 1});

Sorting by a field

	db.collection.find().sort({"field": 1});

Limit the number of records returned by a query

	db.collection.find().limit(3);

Skip over a set of documents

	db.collection.find().skip(3);

List processing

Map over a cursor of results

	db.collection.find().map(function(item) {
	    return item;
	});

Iterate over a cursor of results

	db.collection.find().forEach(function(item) {
	    printjson(item);
	});

Updates

Update over an enumerated list

	db.collection.find().forEach(function(item) {
	    // make changes to item
	    db.collection.save(item);
	});

Update from a query (Mongo update reference)

	db.collection.update({"_id": ObjectId("xxxx")}, 
	                     { $set: { "field": value },
	                       $push: { "subdocument": subdocument } 
	                     });

Deleting

Destroy an entire collection

	db.collection.drop();

Delete a document selectively

	db.collection.remove({"_id": ObjectId("xxxx"));

Utilities

Set the record limit returned to the console

	DBQuery.shellBatchSize = 100