MySQL ↔︎ MongoDB 早見表


Terminology

用語です。

MySQL                 MongoDB              
databases database
table collection
row document
column field

Commands

公式の情報があるので、こちらを見てほしい。→ https://docs.mongodb.com/manual/reference/sql-comparison/

MySQL                 MongoDB                
show databases; show dbs
create database new_db; use new_db
use new_db; use new_db
show tables; show collections
または
db.getCollectionNames()
create table users (name varchar(20)); db.createCollection("users")
drop table users db.users.drop()
desc users; なし
insert into users (name) values ("taro"); db.users.insertOne( { name: "hoge" } )
update users
  set name = "maro"
  where name = "taro";
db.users.updateMany(
  { name: "taro" },
  { $set: { name: "maro" } }
)
select * from users; db.users.find()
select * from users order by name asc; db.users.find().sort( { name: 1 } )
select * from users order by name desc; db.users.find().sort( { name: -1 } )
select * from users limit 1; db.users.find().limit(1)
select count(*) from users; db.users.count()
select name from users where age = 90; db.users.find(
  { age: 90 },
  { name: 1 }
)

Null and Missing field

MySQL の場合はシンプル

MySQL                
select * from users where age is null;
select * from users where age is not null;

MongoDB の場合は null と missing があるので少し複雑

users
{ name: "100",  age: 100 }
{ name: "null",  age: null }
{ name: "missing" }
MongDB                   users.name  
db.users.find( { age: null } ) null, missing
db.users.find( { age: { $ne: null } } ) 100
db.users.find( { age: { $exists: true } } ) 100, null
db.users.find( { age: { $exists: false } } ) missing
db.users.find( { \$and: [
  { age: { $exists: true } },
  { age: null }
] } )
null
db.users.find({ age: { $type: 10 } }) null
db.users.find( { age: { \$not: { $type: 10 } } } ) 100, missing

Docker

Docker のおかげで、それぞれの環境がすぐ使えます。

MySQL
$ docker run --name study-mysql --rm -e MYSQL_ALLOW_EMPTY_PASSWORD=yes mysql:8.0

$ docker exec -it study-mysql bash
root@51c68a47680f:/# mysql
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)
MongoDB
$ docker run --name study-mongo --rm mongo:4.2

$ docker exec -it study-mongo bash
root@c2ab8e8878c3:/# mongo
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

GUI

この辺が王道かと。MongoDB Compass 使いやすいです。