Skip to content

Instantly share code, notes, and snippets.

@raineorshine
Last active August 29, 2015 14:01
Show Gist options
  • Save raineorshine/7d2782e3ded91d356f01 to your computer and use it in GitHub Desktop.
Save raineorshine/7d2782e3ded91d356f01 to your computer and use it in GitHub Desktop.
Mongo - 19 Commands to Get Started

Example

$ mongod &
$ mongo
> use ark
> db.users.insert({ name: 'Noah' })
> db.animals.insert({ name: 'Elephant', type: 'pachyderm' })
> db.animals.insert({ name: 'Tiger', type: 'cat' })
> db.animals.find({ type: 'pachyderm' })
{ "_id" : ObjectId("5370d1b4050f0b6e16263f19"), "name" : "Elephant", "type" : "pachyderm" }

Commands

Shell Commands

show dbs Lists all databases.
use DATABASE_NAME Switches the current database to a specific database.
show collections Lists the collections in the current database.

Database Methods

db.dropDatabase() Removes the current database.

Collection Methods

db.COLLECTION_NAME.count() Returns the number of documents in the collection.
db.COLLECTION_NAME.drop() Drops the collection from the database.
db.COLLECTION_NAME.find() Finds a set of documents that match a given query (returns a cursor).
db.COLLECTION_NAME.findOne() Finds the first document that matches the given query.
db.COLLECTION_NAME.insert() Creates a new document in the collection.
db.COLLECTION_NAME.remove() Deletes documents from the collection.
db.COLLECTION_NAME.update() Modifies a document in the collection.

Cursor Methods

cursor.next() Returns the next document in the cursor.
cursor.hasNext() Returns true if the cursor has documents and can be iterated.
cursor.limit() Constrains the size of a cursor's result set.
cursor.skip() Returns a cursor that begins returning results only after ignoring the first X documents.
cursor.sort() Sorts the documents in the cursor.
cursor.forEach() Applies a function to each document in the cursor.
cursor.map() Applies a function to each document in the cursor and collects the return values in an array.
cursor.toArray() Converts the cursor to an array of documents.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment