MongoDB Shell Cheat Sheet
MongoDB Shell Cheat Sheet
Cheat Sheet
Starting the mongo shell
Mongo shell can be used to connect to local databases, or remote databases running on
another server. If connecting to MongoDB locally, make sure its running in another terminal
window or background process (the `mongod` command).
Code Description
db.apples.find().sort({ price : You can sort the results from a find() op-
-1 }) eration using the sort function. `-1` sorts
descending, `1` sorts ascending.
db.apples.remove({ bad : true}) Removes all bad apples! Finds all apples
with a property of bad set to true, and
removes them.
If you havent already noticed, the mongo shell is a JavaScript REPL. This means you
can use basic JavaScript commands to operate on documents!
var greenest = Finds the greenest apple of them all! Find
db.apples.findOne just one apple document with a country of
({ countryOfOrigin : Ireland }) origin from Ireland.
Note that .findOne() is different - it returns
greenest.price = 10.99 a document, where .find() returns a cursor.
We can assign this document to a variable,
db.apples.save(greenest) make changes, then save it back to the
collection - an update operation.
DANGER ZONE!