このチュートリアルで学ぶこと
✓ MongoDBのセットアップ
✓ CRUD操作
✓ クエリ演算子
✓ インデックス
✓ 集計パイプライン
Step 1: セットアップ
# macOS
brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community
# 接続
mongosh
Step 2: 基本操作
// データベース選択
use myapp
// ドキュメント挿入
db.users.insertOne({
name: "田中太郎",
email: "tanaka@example.com",
age: 30
})
db.users.insertMany([
{ name: "山田花子", email: "yamada@example.com", age: 25 },
{ name: "鈴木一郎", email: "suzuki@example.com", age: 35 }
])
Step 3: クエリ
// 全件取得
db.users.find()
// 条件指定
db.users.find({ age: { $gte: 30 } })
// 演算子
db.users.find({
$and: [
{ age: { $gte: 25 } },
{ age: { $lte: 35 } }
]
})
// 射影
db.users.find({}, { name: 1, email: 1, _id: 0 })
// ソートと制限
db.users.find().sort({ age: -1 }).limit(10)
Step 4: 更新と削除
// 更新
db.users.updateOne(
{ email: "tanaka@example.com" },
{ $set: { age: 31 } }
)
// 複数更新
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
)
// 削除
db.users.deleteOne({ email: "tanaka@example.com" })
Step 5: インデックス
// インデックス作成
db.users.createIndex({ email: 1 }, { unique: true })
// 複合インデックス
db.users.createIndex({ age: 1, name: 1 })
// インデックス確認
db.users.getIndexes()
Step 6: 集計パイプライン
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$userId",
totalAmount: { $sum: "$amount" },
count: { $sum: 1 }
}},
{ $sort: { totalAmount: -1 } },
{ $limit: 10 }
])
Step 7: Node.jsとの連携
import { MongoClient } from 'mongodb';
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('myapp');
const users = db.collection('users');
const result = await users.find({ age: { $gte: 30 } }).toArray();
console.log(result);
await client.close();
まとめ
MongoDBは柔軟なスキーマでJSON形式のドキュメントを扱えます。集計パイプラインで複雑な分析も可能です。
← 一覧に戻る