Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xiongchengqing/65e18f579e63b13230a77648baf26549 to your computer and use it in GitHub Desktop.
Save xiongchengqing/65e18f579e63b13230a77648baf26549 to your computer and use it in GitHub Desktop.
mongodb cheatsheet

MongoDB Cheatsheet

Setup

installation, Ubuntu

https://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | \
    sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
service mongod status
connect
mongo --hostname <hostname> \
	--port <port> \
	-u <username> \
	-p <password> \
	--athenticationDatabase <database>
disconnect
exit
quit()
clear screen
<ctrl + l>
show version
version()
show status
hostInfo()
stats()
serverStatus()
getLastError()
shutdown server
shutdownServer()
configure, Ubuntu

https://docs.mongodb.org/manual/reference/configuration-options/

sudo nano /etc/mongod.conf
debug logs
# print the last 24 lines of the debug log
sudo tail -24 /var/log/mongodb/mongod.log




Databases

list databasess
show dbs
show databases
connect to database
use <database_name>
show current database
db
create database
use <new_database_name>
delete database
db.dropDatabase();
rename database
db.copyDatabase('old_name', 'new_name'); # Copy the database to a new database
use <old_name> # Switch to the database you wish to delete
db.dropDatabase(); # Destroys the selected database




Users

list users
show users
create user
db.AddUser({user: "<username>", pwd: "<password>", roles: ["readWrite"]});
delete user




Collections

show collections
show collections
db.getCollectionNames()
clone database to remote server




Scripting

import database
mongoimport --db <database> \
	-c <collection> \
	--file <filename> \
	--type <type>
backup database
mongodump --db <database> \
	-c <collection>
restore database, from backup
mongorestore --db <database> \
	-c <collection> \
	<bson_file>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment