LoginSignup
223
204

More than 5 years have passed since last update.

MongoDBのデータ構造な簡単な操作など

Posted at

MongoDBの勉強を始めたのでメモしておきます。

MongoDBのデータ構造

--MongoDB
  +--データベース
  |  +--コレクション
  |  |  +--ドキュメント
  |  |  +--ドキュメント
  |  |
  |  +--コレクション
  |  |  +--ドキュメント
  | 
  +--データベース
  |  +--コレクション

RDBとMongoDBのデータ構造の比較

  • 以下表を参照。
RDBでの呼称 MongoDBでの呼称
database database
table collection
row document
column field
index index
primary key _id field
  • _idの値について、自動的に一意な文字列が採番されます。

MySQLと比較したクエリ

データベース操作

MySQL MongoDB
SHOW DATABASES; show dbs
USE testdb; use testdb
CREATE DATABASE testdb; useコマンドで自動生成
DROP DATABASE testdb; use testdb
db.dropDatabase()
index index
DESC testdb; なし

コレクション操作

MySQL MongoDB
CREATE TABLE products (...); 自動生成 または
db.createCollection("products")
ALTER TABLE products ADD ...; 自動生成
SHOW TABLES; show collections
DROP TABLE products; db.products.drop()
TRUNCATE TABLE products; db.products.remove()

ドキュメント操作

選択

MySQL MongoDB
SELECT * FROM products; db.products.find()
SELECT name FROM products
WHERE category='A'
AND stock<=10
ORDER BY name;
db.products.find(
{
category : 'A' ,
stock : { $lte : 10 }
},
{ name : 1 }
).sort({ name : 1})
SELECT COUNT(*) FROM products; db.products.count()
SELECT COUNT(*) FROM products
WHERE name LIKE "%camera%"
OR category='C';
db.products.find(
{
$or : [
{ name : /camera/ },
{ category : 'C' }
]
}
).count()
SELECT COUNT(stock) FROM products; db.products.find({
stock : { $exists : true }
}).count()
SELECT * FROM products LIMIT 1; db.products.findOne()
SELECT * FROM products LIMIT 5; db.products.limit(5)

挿入

MySQL MongoDB
INSERT INTO products
VALUES('A',"camera case",5);
db.products.insert(
{
category : 'A' ,
name : "camera case" ,
stock : 5
}
)

更新

MySQL MongoDB
UPDATE products SET
stock=10
WHERE category='A';
db.products.update(
{ category : 'A' },
{ $set : { stock : 10 } },
false,
true
)
UPDATE products SET
stock=stock+10
WHERE category='A';
db.products.update(
{ category : 'A' },
{ $inc : { stock : 10 } },
false,
true
)

削除

MySQL MongoDB
DELETE FROM products
WHERE name="camera case";
db.products.remove(
{name : "camera case"}
)

参考にしたサイト

223
204
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
223
204