Basic MongoDB command
Chun-Jie Liu · 2022-06-28
Simple manual for MongoDB
Install a MongoDB on a new server to config the /etc/mongod.conf
file. You may need to change the storage.dbPath
(default /data/mongodb/), net.port
(default 27017) and net.bindIp
(default 0.0.0.0).
Create an admin user
mongo # or mongo --port 27017
# in the mongo shell
use admin;
db.createUser({
user: "adminuser",
pwd: "complexpassword",
roles: [{
role: "readWriteAnyDatabase",
db: "admin"
}, {
role: "userAdminAnyDatabase",
db: "admin"
}]
});
# login again to use admin
use admin;
db.auth("adminuser", "complexpassword")
Create a regular user for specific database
mongo
# in the mongo shell
# login with admin user
db.auth("adminuser", "complexpassword")
use newdatabasename;
# create a write user
db.createUser({
user: "username_write",
pwd: "username_write_password",
roles: [{
role: "readWrite",
db: "newdatabasename"
}]
});
# create a read user
db.createUser({
user: "username_read",
pwd: "username_read_password",
roles: [{
role: "read",
db: "newdatabasename"
}]
});
# use regular user to access to login
db.auth("username_write", "newdatabasename")
Drop regular user
mogno
db.auth("adminuser", "complexpassword")
db.dropUser("username_read")
Collection export and restore
# backup database
mongodump -h localhost --port port -u username -p password -d databasename -o outputpath
mongorestore -h localhost --port port -u username -p password -d databasename --drop filepath
## backup collections
mongoexport -h localhost --port port -u username -p paswd -d databasename -c collection -f field -q query --type json -o filename.json --jsonArray --pretty
mongoimport -h localhost --port port -u username -p passwd -d databasename -c collection --upsert --drop filename.json
Using R/Python to collect MongoDB and updata collections
The very R example and Python example.