MySQL: Database -> Table -> Row -> Column e Value -> Index
MongoDB: Database -> Collection -> Document -> Field e Value -> Index
No MongoDB os dados são do tipo BSON, similar ao JSON. Todo document possui um field 'id', gerado automaticamente, que serve como uma primary key, para relacionar e identificá-lo. Cada document tem um field com value, possuindo um tipo específico.
{
_id: ObjectId("509a8fb2f3f4948bd2f983a0"),
nome: "fulano",
idade: 55,
status: 'A'
}
Start: sudo systemctl start mongod
Status: sudo systemctl status mongod / sudo systemctl enable mongod
Stop: sudo systemctl stop mongod
Restart: sudo systemctl restart mongod
Shell/Status: mongo
show dbs: ver dbs existentes
use nomeDB: criar/acessar BD
show collections: ver collections do db em questão
exit: sai do shell
db.getUsers(): lista usuários do mongo
db.createUser({user:"nome",pwd:"senha",customData:{db:"aula"},roles:[{role:"readWrite",db:"aula"}]})
//cria user com regra de acesso, customData é o bd exclusivo em que o user pd acessar(pd ser db,collection,document...)
db.auth("nomeUser","senhaUser"): Autentica user(feedback 1 para autenticado / 0 para barrado)
db.dropUser("nomUser"): Deleta user
MySQL
CREATE DATABASE teste
CREATE TABLE people (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
user_id Varchar(30),
age Number,
status char(1),
PRIMARY KEY(id)
)
MongoDB
use teste (cria db automaticamente qndo cria collection nele)
db.createCollection("people")
db.people.insertOne({
user_id: "abc123",
age: 55,
status: "A"
})
MySQL
ALTER TABLE people ADD join_date DATETIME
ALTER TABLE people DROP COLUMN join_date
CREATE INDEX idx_user_id_asc ON people(user_id)
CREATE INDEX idx_user_id_asc_age_desc ON people(user_id, age DESC)
MongoDB
db.people.updateMany( { },{$set:{join_date:new Date()} })
db.people.updateMany( { },{$unset:{"join_date":""} })
db.people.createIndex( {user_id:1} )
db.people.createIndex( {user_id:1,age:-1} )
MySQL
DROP TABLE people
DROP DATABASE teste
MongoDB
db.people.drop()
use teste; db.dropDatabase()
MySQL
INSERT INTO people(user_id,age,status) VALUES ("bcd001",45,"A")
INSERT INTO people(user_id,age,status) VALUES ("bcd001",45,"A"),("vvv",30,"B")
MongoDB
db.people.insertOne({ user_id:"bcd001", age:45, status:"A" })
db.people.insertMany( {user_id:"bcd001",age:45,status:"A"},{user_id:"vvv",age:30,status:"B"} )
MySQL
1.SELECT * FROM people
2.SELECT id,user_id,status FROM people
3.SELECT user_id,status FROM people
4.SELECT * FROM people WHERE status = "A"
5.SELECT user_id,status FROM people WHERE status = "A"
6.SELECT * FROM people WHERE status != "A"
7.SELECT * FROM people WHERE status = "A" AND age = 50
8.SELECT * FROM people WHERE status = "A" OR age = 50
9.SELECT * FROM people WHERE age > 25
10.SELECT * FROM people WHERE age < 25
11.SELECT * FROM people WHERE age > 25 AND age <= 50
12.SELECT * FROM people WHERE user_id like "%bc%"
13.SELECT * FROM people WHERE user_id like "bc%"
14.SELECT * FROM people WHERE status = "A" ORDER BY user_id ASC
15.SELECT * FROM people WHERE status = "A" ORDER BY user_id DESC
16.SELECT COUNT(*) FROM people
17.SELECT COUNT(user_id) FROM people
18.SELECT COUNT(*) FROM people WHERE age > 30
19.SELECT DISTINCT(status) FROM people
20.SELECT * FROM people LIMIT 1
21.SELECT * FROM people LIMIT 5 SKIP 10 EXPLAIN SELECT * FROM people WHERE status = "A"
MongoDB
1.db.people.find()
1.1.db.aluno.find().pretty() //em formato json
2.db.people.find({ },{ user_id:1, status:1 })
3.db.people.find({ },{ user_id:1, status:1, _id:0 })
4.db.people.find({ status:"A" })
5.db.people.find({ status:"A" },{ user_id:1, status:1, _id:0 })
6.db.people.find({ status: { $ne:"A" } })
7.db.people.find({ status:"A", age:50 })
8.db.people.find({ $or: [ {status:"A"} , {age:50} ] })
9.db.people.find({ age: {$gt:25} })
10.db.people.find({ age: {$lt:25} })
11.db.people.find({ age: { $gt:25, $lte:50 } })
12.db.people.find( { user_id:/bc/ } )
13.db.people.find( { user_id:/^bc/ } )
14.db.people.find( {status:"A"} ).sort( {user_id:1} )
15.db.people.find( {status:"A"} ).sort( {user_id:-1} )
16.db.people.count()
17.db.people.count( { user_id: {$exists:true} } )
18.db.people.count( { age: {$gt:30} } )
19.db.people.aggregate([ { $group:{_id:"$status"} } ])
20.db.people.findOne()
21.1.db.people.find().limit(5).skip(10)
21.2.db.people.find( {status:"A"} ).explain()
MySQL
UPDATE people SET status = "C" WHERE age > 25
UPDATE people SET age = age + 3 WHERE status = "A"
MongoDB
updateOne: Atualiza somente o 1º document
db.people.updateMany({ age: {$gt:25} },{ $set: {status:"C"} })
db.people.updateMany({ status:"A" } ,{ $inc: {age:3} })
db.tableX.renameCollection("tableY") //renomear collection
MySQL
DELETE FROM people WHERE status = "D"
DELETE * FROM people
MongoDB
deleteOne: Deleta somente o 1º document
db.people.deleteMany( {status:"D"} )
db.people.deleteMany({})
Ou faz tudo, ou não faz nada
try {db.characters.bulkWrite([
{insertOne: {"document": {"_id":4, "char":"Dithras", "class":"barbarian", "lvl":4}}},
{insertOne: {"document": {"_id":5, "char":"Taeln", "class":"fighter", "lvl":3}}},
{updateOne: {"filter": {"char":"Eldon"},"update": {$set: {"status":"Critical Injury"} }}},
{deleteOne: {"filter": {"char":"Brisbane"} }},
{replaceOne: {"filter": {"char":"Meldane"},"replacement": {"char":"Tanys", "class":"oracle", "lvl":4 }}}]);
}catch(e) {print(e);}
var myCursor = db.users.find( {type:2} );
myCursor
var myCursor = db.users.find( {type:2} );
while (myCursor.hasNext()) {
print(tojson(myCursor.next()));
}
var myCursor = db.users.find( {type:2} );
myCursor.forEach(printjson);
var myCursor = db.inventory.find( {type:2} );
var documentArray = myCursor.toArray();
var myDocument = documentArray[3]; //print em array(aqui o index3)
var myCursor = db.users.find( {type:2} );
var myDocument = myCursor[1]; //usa menos memória
var myCursor = db.users.find().noCursorTimeout(); //troca o timeout do cursor(padrão é 10min)
var myCursor = db.inventory.find();
var myFirstDocument = myCursor.hasNext() ? myCursor.next() : null;
myCursor.objsLeftInBatch(); //com if's
Importa arquivo para determinada collection de db. Headerline pega os títulos das colunas e transforma em nome de parâmetros nos documents.
mongoimport -d dbNome -c nomeCollection --type csv --file arquivo.csv --headerline
Elaborado por Mateus Schwede
ubsocial.github.io