MongoDB Command-Line Commands

Logging in

$ mongo u## -u u## -p

Getting help/Logging out

> help() [or just help] [shows some "high level" MongoDB help]
> exit() [or .exit or just exit]
> quit() [or just quit]
> CTRL+C CTRL+C
> CTRL+D

Linux command-line commands available from within MongoDB

> version() [return current version of mongo shell]
> process.cwd() [show the curent working directory]
> fs.readdirSync(".") [list contents of current working directory]
> fs.mkdirSync( , { recursive: true } )
  [create subdirectory in current working directory]
> process.chdir() [change to the given directory]
> fs.readFileSync(, 'utf8')
  [display file in current working directory]
> fs.unlinkSync() [delete file]
> os.hostname() [shows name of host, as if you couldn't guess]

Keyboard shortcuts

> CTRL+L [clears screen and places current command on top line]
> cls [also clears the screen, though it's not a Linux command]
> CTRL+U [clears line up to but not including cursor position]
> CTRL+A [moves cursor to beginning of line]
> CTRL+E [moves cursor to end of line]
> ALT+D [delete the next word]

Using MongoDB as a calculator (just because you can)

> 2 + 3
> n = 7
> n * 5

Exploring after login

> db.version() [shows the mongodb version number]
> show dbs [just shows your u## and test]
> show users [not authorized on our system]
> use DATABASE_NAME [switches database, but only alternative is test]
> db [shows current database]
> db.stats() [shows some information about the current database]
> show collections [lists names of all collections in current database]
> db.help() [shows list of db methods]
> db.collection_name.help() [shows help for the particular collection]

Creating a database collection

> db.createCollection("collection_name"[, options])

Inserting data into a database collection

> load("mongo_data.js")
  [works if file contains lines of the form
  db.COLLECTION_NAME.insert(single_JSON_object)
  or lines of the form
  db.COLLECTION_NAME.insertMany(array_of_JSON_objects)
  and lines like these work at the MongoDB prompt as well]

Reading data from a database and database collections

> db.getCollectionNames() [lists collection names in current database]
> db.COLLECTION_NAME.find()
  [lists all documents in the collection, 20 at a time by default]
> config.set("displayBatchSize", 10)
  [to change display number from 20 to 10, for example]
> db.COLLECTION_NAME.find(query_selector)
[finds all documents in the collection that match the query]
> db.COLLECTION_NAME.find({key: value[, key: value ...]})
> db.COLLECTION_NAME.find({author: "Winston Churchill"})
> db.COLLECTION_NAME.find().pretty() [displays more readable output]
> db.COLLECTION_NAME.find().sort({"key": 1}) [sort ascending]
> db.COLLECTION_NAME.find().sort({"key": -1}) [sort descending]

> db.COLLECTION_NAME.find({"key": "value"})
[finds all documents matching the key/value query selector]
> db.COLLECTION_NAME.findone({"key": "value"})
[finds one document matching the key/value query selector]

> db.COLLECTION_NAME.find({"key1": "value1", "key2": "value2"})
[find all documents matching multiple criteria]

Deleting documents from a collection and deleting an entire collection

> db.COLLECTION_NAME.remove(query) [removes all documents matching query]
> db.COLLECTION_NAME.remove(query,1) [removes first matching document]

> db.COLLECTION_NAME.remove({})
  [drops/deletes all documents but leaves the empty collection]
> db.COLLECTION_NAME.drop() [drops/deletes the entire collection]

Renaming a collection

> db.OLD_NAME.renameCollection("new_name")

Updating a document in a collection (example)

> db.quotes_mongo.update({'_id':1}, {$set:{'text':'Some new text ...'}})

The limit(), skip(), count() and sort() methods

> db.COLLECTION_NAME.find().limit(NUMBER)
> db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
> db.COLLECTION_NAME.count()
> db.COLLECTION_NAME.find(query).count()
> db.COLLECTION_NAME.find().sort({KEY:type})

Linux command-line commands available outside MongoD
Importing and exporting JSON data to/from MongoDB
(password authorization required)

$ mongoimport --username u## --db u## --file filename.json
$ mongoimport --username u## --db u## --collection collection_name --file filename.json
$ mongoexport --username u## --db u## --collection collection_name
              --out filename.json [--sort='{_id:1}']

Miscellaneous external commands

$ mongo --quiet --eval "db.serverStatus()" | more
$ mongo --eval "DBQuery.shellBatchSize=100; db.foo.find()"

Connecting PHP with MongoDB

//Step 1: Include Composer's autoloader file to connect PHP and MongoDB.
include('/var/shared/vendor/autoload.php');

//Step 2: Access username and password from outside location.
include($_SERVER["CONTEXT_DOCUMENT_ROOT"] . '/../htpasswd/mongodb.inc');

//Step 3: Connect to the MongoDB database.
$client = new MongoDB\Client("mongodb://$username:$password@localhost/u30");

//Step 4: Connect to a collection, then a document, within the database.
$collection = $client->u30->quotes_mongo;
$result = $collection->find( [ 'author' => 'Winston Churchill' ] );
foreach ($result as $entry)
{
    echo $entry['_id'], ': ', $entry['text'], "<br>";
}

MongoDB port number: 27017

And if you have MongoDB installed on Windows:

> db.shutdownServer({force: <boolean>, timeoutSecs: <int>})
[Must issue this operation against the admin database]

> net stop MongoDB [if it's a Windows service]