Learning MongoDB

Learning MongoDB

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

(4 tomatoes: install + crud)

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 #

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

to Run #

# start service:
sudo service mongod start
# check:
cat /var/log/mongodb/mongod.log
# start shell:
mongo
# or:
mongo --host 127.0.0.1:27017
# or:
mongo databaseName

ref doc install

Crud Usage #

crud in mongo shell #

// connect to a db (create automatically if not existing):
use myDatabase
// insert:
db.myCollection.insert([
    {'name': 'Alice', 'age': 30},
    {'name': 'Bill', 'age': 25},
    {'name': 'AAA', 'age': 22},
    {'name': 'Bob', 'age': 35}
]);
// read:
db.myCollection.find()
db.myCollection.find({name:"AAA"})
// update field(s) for selected records:
db.myCollection.update({name:"AAA"}, { $set: {last_name:"aaa", nick_name:["small_a", "big_a"]} })
db.myCollection.find()
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" })
db.myCollection.find()
// delete:
db.myCollection.remove({name:"AAA"})
db.myCollection.find()
// estimate dump size in bytes:
db.stats().dataSize
show dbs
show collections

dump in bash #

mongodump -d myDatabase # -d [db name]

Will dump into a folder named dump.

drop db in mongo #

use myDatabase
db.dropDatabase()
// verify it is deleted (cannot find anything):
db.myCollection.find()
db.myCollection.find().limit(2)

restore in bash #

mongorestore dump_folder_name
mongo myDatabase

check in mongo:

db.myCollection.find().skip(1).limit(1);

ref DigitalOcean ind().skip(1).limit(1);

[ref DigitalOcean](https://is.gd/7hgiO3)