MongoDB Command-Line Commands
Logging in
$ mongo -uu## --authenticationDatabase u30 -p
[Don't use above command; drops you into test database as default.]
[Use above command instead, which drops you into u## database.]
$ mongo u## -uu## -p
Getting help/Logging out
> help [shows some "high level" MongoDB help]
> exit
> quit()
> CTRL+C
Linux command-line commands available from within MongoDB
> pwd() [show the curent working directory]
> ls() [list contents of current working directory]
> mkdir("dir_name") [create subdirectory in current working directory]
> cd("dir_name") [change to the given directory]
> cat("filename") [display file in current working directory]
> hostname() [shows name of host, as if you couldn't guess]
> 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 [not authorized on our system; you have only 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.help [shows the help function code ... you don't want to do this]
> help [but this also works to get help]
> db.collection_name.help() [shows help for the particular collection]
Creating a database collection
> db.createCollection(name)
> db.createCollection(name, options) [see documentation for options]
Inserting data into a database collection
> load("mongo_data.js")
[works if file contains lines of the form
db.COLLECTION_NAME.insert(document_in_JSON-format)
and lines like this 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]
> db.COLLECTION_NAME.find().pretty() [same, but 20 at a time and with better formatting]
> db.COLLECTION_NAME.find().toArray() [lists an array of all documents with good formatting]
> DBQuery.shellBatchSize=# [to change default=20 number of display docs]
> db.COLLECTION_NAME.find(query_selector)
[finds all documents in the collection that match the query]
[The following three commands are, in fact, equivalent.]
> db.COLLECTION_NAME.find() [shows all documents, no particular order]
> db.COLLECTION_NAME.find({})
> db.COLLECTION_NAME.find(null)
> 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 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]