MIKESTOWE.COM

you are here

MongoDB Query Cheat Sheet

A quick cheat sheet of common MongoDB commands and queries.

List all databases

show dbs


Determine which database to use for queries

use %database_name%


List all collections (tables) within the selected database

show collections


Find one document (row) from the collection

db.%collection_name%.findOne()


Find one document with a WHERE statement using And

db.%collection_name%.findOne( { “key” : “value”, “key” : “value” } )


Find many with a WHERE statement using And

db.%collection_name%.find( { “key” : “value”, “key” : “value” } )


Get the Count of a Find

db.%collection_name%.find( { “key” : “value”, “key” : “value” } ).count()


Find many with a WHERE statement using And and Sorting ASC
Note: you can use “1” for Ascending or “-1” for Descending

db.%collection_name%.find( { “key” : “value”, “key” : “value” } ).sort(“key” : 1)


Find many with a WHERE statement using And and Sorting ASC and with a Limit

db.%collection_name%.find( { “key” : “value”, “key” : “value” } ).sort(“key” : 1).limit(10)


Find many with a WHERE statement using And and Sorting ASC and with an OFFSET and a Limit

db.%collection_name%.find( { “key” : “value”, “key” : “value” } ).sort(“key” : 1).skip(5).limit(10)


Find scores where kind is equal to “exam” or “quiz” (in order of efficiency)

db.scores.find( { “kind” : { $in : [“exam”, “quiz”] } } )
db.scores.find( {$or : [{kind : “quiz”}, {kind : “exam”}] } )
db.scores.find( { “kind” : /exam|quiz/ })


Insert document (record) into Collection

db.%collection_name%.insert( { “key” : “value”, “key” : “value”, “key” : “value” } )


Replace a single document (record) in Collection
Warning, update REPLACES the matching record, any field not updated will be deleted

db.%collection_name%.update( { “search_key” : “search_value” }, { “update_key” : “update_value” } )


Update a single document (record) in Collection

db.%collection_name%.update( { “search_key” : “search_value” }, { $set : { “update_key” : “update_value” } } )


Update multiple documents (records) in Collection

db.%collection_name%.update( { “search_key” : “search_value” }, { $set : { “update_key” : “update_value” } }, { “multi” : true } )


Insert or Update document (record) in Collection

db.%collection_name%.update( { “search_key” : “search_value” }, { $set : { “update_key” : “update_value” } }, { “upsert” : true } )


Delete documents (records) from Collection
Warning, unlike update, remove does not have a limit or multi setting

db.%collection_name%.remove( { “search_key” : “search_value” } )


Create an Index on a Collection
Note: you can use “1” for Ascending or “-1” for Descending

db.%collection_name%.ensureIndex( { “search_key” : 1 } )


Share this Page:
Facebook Twitter Linkedin Reddit Tumblr Email

Leave a Reply

Your email address will not be published. Required fields are marked *