Learning MongoDB

Learning MongoDB

2018-01-01. Category & Tags: MongoDB, Basics, CRUD

(4 tomatoes: install + crud)

Note, --host is the default for most cmd, but the bound IP may be NOT or localhost, it can be another NIC with LAN-only instead.

Install #

ref doc install

to install #

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5 && \
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list && \
sudo apt-get update && \
sudo apt-get install -y mongodb-org

to prevent update #

dpkg -l | grep mongo
echo "mongodb-org hold" | sudo dpkg --set-selections
echo "mongodb-org-server hold" | sudo dpkg --set-selections
echo "mongodb-org-shell hold" | sudo dpkg --set-selections
echo "mongodb-org-mongos hold" | sudo dpkg --set-selections
echo "mongodb-org-tools hold" | sudo dpkg --set-selections

run the server #

# start service:
sudo service mongod start
# check:
cat /var/log/mongodb/mongod.log

connect from the client to the server and open mongo-shell (bash) #

# start shell:
# or:
mongo --host
# or:
mongo database_name

authenticate a user #

after getting into a mongo-shell:

db.auth({ user: "my_username", pwd: "my_pwd" });

otherwise, in bash (NOT tested):

mongo -v -u $user -p $pwd --host mong_bind_ip:27017 database_name

use (select, connect to) a specific database #

use my_database

Note, after use xxx, the special variable db will refer to the selected db.

Crud Usage #

crud in mongo shell #

// use a db (create automatically if not existing):
use my_database
// insert:
    {'name': 'Alice', 'age': 30},
    {'name': 'Bill', 'age': 25},
    {'name': 'AAA', 'age': 22},
    {'name': 'Bob', 'age': 35}
// read:
// update field(s) for selected records:
db.myCollection.update({name:"AAA"}, { $set: {last_name:"aaa", nick_name:["small_a", "big_a"]} })
db.myCollection.find({nick_name:"big_a"}) // nested matching
// update record(s) for selected records (deleting other fields)
db.myCollection.update({name:"AAA"}, { last_name: "bbb" })
// delete:
// estimate dump size in bytes:
show dbs
show collections

dump in bash #

mongodump -d my_database # -d [db name]

Will dump into a folder named dump.

drop (delete) collections and/or a db with its users (mongo-shell) #

opt1: drop (delete) all collections in a db, but keep users:

use my_database;
db.getCollectionNames().forEach(function (c) {
  if (c.indexOf("system.") == -1) db[c].drop();

opt2: drop (delete) all content related to a db, including the db and its users:

use my_database;

// verify it is deleted (cannot find anything):

opt3: drop all databases except admin,config,local:

OBS: failed during test !!!, “not authorized on … to execute command dropDatabase …”.

  .databases.map((d) => d.name)
  .filter((n) => ["admin", "config", "local"].indexOf(n) == -1)
  .map((n) => db.getSiblingDB(n).dropDatabase());

ref: https://stackoverflow.com/a/69230279

restore #

in bash:

mongorestore dump_folder_path # will NOT update existing/duplicate document
mongorestore --drop dump_folder_path  # will DROP any collection/database that exists in backup before restore

mongorestore --username $user --password $pwd --authenticationDatabase admin dump_dir
mongorestore --username $user --password $pwd --authenticationDatabase admin --db exampleDB dump_dir/my_database

in mongo shell, check:


ref DigitalOcean

Manage Users & Roles (Role==Permission) #

All users’ information is saved in admin. So, first, we select which users to manage, use admin to manage all users, or use my_db to manage users related to the specific database “my_db”.

use admin
use my_database

db.getUser("tom"); // will show the user's roles/permissions

// change password
db.changeUserPassword("tom", "secretpassword");
// or
db.changeUserPassword("tom", passwordPrompt());

ref: https://www.prisma.io/dataguide/mongodb/configuring-mongodb-user-accounts-and-authentication