SQLからMongoDB入門(SQL文との対応)

MongoDBでselect * from hogehoge


big-data-1667212_640

MongoDBでselect * from hogehogeってどうやるんだっけ?

答えはdb.hogehoge.find()です。

このようなSQLとMongoDBの対応関係を一覧で見れれば良いなと思ってまとめてみました。

RDBとMongoDBの用語

RDBでの呼称 MongoDBでの呼称
database database
table collection
row document
column field
index index
primary key _id

よく使うコマンド

確認系(use, show)

RDBのコマンド MongoDBのコマンド
use [データベース名] use [データベース名]
show databases show dbs
show tables show collections

検索系(select ~)

RDBのコマンド MongoDBのコマンド
select * from [コレクション名] db.[コレクション名].find()
select * from [コレクション名] where x=4 db.[コレクション名].find({x:4})
select j from [コレクション名] where x=4 db.[コレクション名].find({x:4}, {j:1})
select * from [コレクション名] limit 1 db.[コレクション名].findOne()
select * from [コレクション名] where x > 1 db.[コレクション名].find({x: {\$gt: 1}})
select * from [コレクション名] where x < 3 and x > 1 db.[コレクション名].find({x: {\$gt: 1, \$lt: 3}})
select * from [コレクション名] limit 3 db.[コレクション名].find().limit(3)
select * from [コレクション名1] inner join [コレクション名2] on x = x p = db.[コレクション名1].findOne({x:1}); db.[コレクション名2].findOne( { _id : p.x } )
select * from [コレクション名] order by x desc db.[コレクション名].find().sort({x:-1})
select count(*) from [コレクション名] db.[コレクション名1].find({x:1}).count()
explan select * from [コレクション名] where x = 1 db.[コレクション名].find({x:1}).explain()

書き換え系(insert, update, delete)

RDBのコマンド MongoDBのコマンド
insert into [コレクション名] (x) value( 3 ) t = { x : 3 }; db.[コレクション名].insert(t)
update [コレクション名] set y = 1 where x = 1 db.[コレクション名].update( { x:1 }, { $set: { y : 1 } } )
delete from [コレクション名] where x = 1 db.[コレクション名].remove({x:1}); t = { x : 3 }

インデックス系

RDBのコマンド MongoDBのコマンド
create index hoge on [コレクション名] (x) db.[コレクション名].ensureIndex({x:1})
create index hoge on [コレクション名] (x,y) db.[コレクション名].ensureIndex({x:1, y:1})
create unique index hoge on [コレクション名] (x) db.[コレクション名].ensureIndex({x: 1}, {unique: true})
drop index hoge db.[コレクション名].dropIndex({x: 1, y: -1})

コメント

タイトルとURLをコピーしました