Skip to content

MongoDB チートシート

大量データの保存に適した NoSQL ドキュメントデータベース。

01

はじめに

MongoDB への接続

mongosh は最新の MongoDB Shell です(従来の mongo shell の後継)。接続文字列は mongodb://[user:pass@]host[:port]/[db][?options] という URI 形式で書きます。/admin データベースがデフォルトの認証データベースです。URI の末尾にデータベース名を付ければ、特定のデータベースへ直接接続できます。

mongodb
# connect to a local server on default port
mongosh

# connect to a specific host and port
mongosh "mongodb://localhost:27017"

# connect with authentication
mongosh "mongodb://user:pass@localhost:27017/admin"

# connect to a specific database directly
mongosh "mongodb://localhost:27017/mydb"

# show connection info
db.getMongo().getDBNames()

データベースの基本

MongoDB はデータベースやコレクションを遅延生成します — 最初のドキュメントを挿入して初めて実体が現れます。'use mydb' はコンテキストを切り替えるだけで、データを書き込むまでデータベースは作られません。show dbs には空のデータベースは表示されません。dropDatabase はすべてのコレクションとデータを完全に削除します。

mongodb
# show all databases
show dbs

# switch to (or create) a database
use mydb

# show the current database
db

# create is implicit: inserting into a
# non-existent collection creates both the
# collection and the database

# drop the current database
db.dropDatabase()

コレクション

コレクションは SQL のテーブルに相当し、ドキュメントを保持します。最初の insert で自動作成されますが、createCollection を使えば capped(古いドキュメントを上書きする固定サイズのコレクション — ログ向き)のようなオプションを設定できます。stats() はストレージサイズ、ドキュメント数、インデックスの詳細を表示します。

mongodb
# list collections in current database
show collections
db.getCollectionNames()

# create a collection explicitly with options
db.createCollection("users", {
  capped: true,
  size: 5242880,
  max: 5000
})

# rename a collection
db.users.renameCollection("accounts")

# drop a collection
db.users.drop()

# get collection stats
db.users.stats()

BSON データ型

BSON は JSON をアプリケーションに不可欠な型で拡張したものです: ObjectId(12 バイトの一意 ID)、ISODate、NumberDecimal(金銭計算に使える正確な 10 進数 — 浮動小数点の丸め誤差を回避)、NumberLong(64 ビット整数)、BinData(バイナリ)など。通貨には NumberDecimal を使うと昔ながらの浮動小数点誤差を避けられます。

mongodb
# MongoDB stores BSON (binary JSON) with rich types
{
  _id: ObjectId("65a1b2c3d4e5f6a7b8c9d0e1"),
  name: "Alice",                       // String
  age: 30,                             // Int32
  score: NumberLong(9007199254740992), // Int64
  price: NumberDecimal("19.99"),       // Decimal128 (exact money)
  active: true,                        // Boolean
  birthday: ISODate("1995-08-15"),     // Date
  tags: ["red", "blue"],               // Array
  meta: { views: 100 },                // Embedded document
  data: BinData(0, "aGVsbG8="),        // Binary
  id: UUID("...")                      // UUID
}

シェルヘルパーとヘルプ

mongosh は完全な JavaScript をサポートするので、シェル上でループや関数、変数も書けます。.pretty() は出力を読みやすく整形します(mongosh ではデフォルト)。load() は .js ファイルをシェルのコンテキストで実行します — 繰り返し使う管理スクリプトに便利です。db.collection.help() で利用可能な全メソッドを一覧できます。

mongodb
# get help on database methods
db.help()

# get help on collection methods
db.users.help()

# list common shell commands
help

# pretty-print query results
db.users.find().pretty()

# print JSON in a compact form
db.users.find().toArray()

# execute a JavaScript file
mongosh --file script.js
load("script.js")
02

CRUD 操作

ドキュメントの挿入

_id(ObjectId)を指定しなければ MongoDB が自動生成します。_id はコレクション内で一意である必要があり、重複すると書き込みエラーになります。ordered:false を付けると insertMany はエラーが起きても残りのドキュメントの挿入を続けるため、大量ロードのスループットが上がります。

mongodb
# insert a single document
db.users.insertOne({
  name: "Alice",
  email: "[email protected]",
  age: 30
})

# insert multiple documents
db.users.insertMany([
  { name: "Bob", age: 25 },
  { name: "Carol", age: 28 }
])

# insert with a custom _id
db.users.insertOne({ _id: 1, name: "Dave" })

# ordered insert (stops on error) vs unordered
db.users.insertMany(docs, { ordered: false })

find / クエリ

find() はカーソル(遅延評価)を返し、findOne() は単一のドキュメントか null を返します。プロジェクションで返すフィールドを制御できますが、包含と除外は混在できません(_id を除く)。1 で含めて 0 で除外します。countDocuments が正確で、古い count() は条件付き件数としては非推奨です。

mongodb
# find all documents
db.users.find()

# find with a filter
db.users.find({ age: 30 })
db.users.find({ "address.city": "NYC" })

# find one matching document
db.users.findOne({ name: "Alice" })

# projection: include/exclude fields
db.users.find({}, { name: 1, age: 1, _id: 0 })
db.users.find({}, { email: 0 })

# count matching documents
db.users.countDocuments({ age: { $gte: 18 } })

ドキュメントの更新

updateOne/updateMany は更新演算子($set、$inc など)で特定のフィールドだけを変更します。replaceOne は _id 以外のドキュメント全体を置き換えます。upsert:true を付けると一致するドキュメントがない場合に新規作成します — 「作成または更新」パターンに便利です。フィールドの更新には必ず $set を使い、素のオブジェクトを渡すとドキュメント全体が置き換わります(旧来の動作)。

mongodb
# update one document
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 31, status: "active" } }
)

# update many documents
db.users.updateMany(
  { status: "pending" },
  { $set: { status: "active" } }
)

# replace an entire document (keeps _id)
db.users.replaceOne(
  { name: "Alice" },
  { name: "Alice", age: 32, city: "NYC" }
)

# upsert: insert if no match found
db.users.updateOne(
  { name: "Eve" },
  { $set: { age: 22 } },
  { upsert: true }
)

更新演算子

更新演算子はドキュメント単位でフィールドをアトミックに変更します。$inc は並行処理でも安全です(読み取り・変更・書き込みの競合が起きません)。$min/$max は新しい値がより小さい/大きい場合だけ更新します。$currentDate は「最終更新」タイムスタンプに便利です。複数の演算子は 1 回の更新で組み合わせられます。

mongodb
# $set and $unset
db.users.updateOne({n:"A"}, { $set: {age:30}, $unset: {temp:""} })

# $inc increments a numeric field
db.users.updateOne({n:"A"}, { $inc: {views: 1} })
db.users.updateOne({n:"A"}, { $inc: {balance: -50} })

# $rename a field
db.users.updateOne({n:"A"}, { $rename: {n: "name"} })

# $min / $max keep the smaller/larger value
db.users.updateOne({n:"A"}, { $min: {lowScore: 80} })

# $mul multiply the field value
db.users.updateOne({n:"A"}, { $mul: {price: 1.1} })

# $currentDate sets to current date
db.users.updateOne({n:"A"}, { $currentDate: {updatedAt: true} })

ドキュメントの削除

deleteOne は最初の一致を、deleteMany は一致したすべてを削除します。deleteMany({}) はコレクションを空にしますがインデックスは残ります(インデックス定義を維持したい場合は drop +再作成より速い)。findOneAndDelete は削除したドキュメントをアトミックに返します。削除は取り消せません — 必ずフィルターを慎重に確認しましょう。

mongodb
# delete one matching document
db.users.deleteOne({ name: "Alice" })

# delete all matching documents
db.users.deleteMany({ status: "inactive" })

# delete all documents in a collection
db.users.deleteMany({})

# findAndDelete: return the deleted document
db.users.findOneAndDelete({ name: "Bob" })

# remove is deprecated, prefer deleteOne/deleteMany
db.users.remove({ name: "Bob" }, { justOne: true })

配列更新演算子

$push は末尾に追加し(重複を許可)、$addToSet は重複を排除して追加します。$pull は条件に一致する要素を削除します。位置演算子($)はクエリがマッチした最初の配列要素を参照します — インデックスを知らなくても特定の配列要素を更新できる必須テクニックです。$[] はすべての配列要素を更新します。

mongodb
# $push append to an array
db.users.updateOne({n:"A"}, { $push: {tags: "new"} })

# $push with $each for multiple values
db.users.updateOne({n:"A"}, { $push: {tags: { $each: ["x","y"] } } })

# $addToSet adds only if not already present
db.users.updateOne({n:"A"}, { $addToSet: {tags: "x"} })

# $pull remove all matching array elements
db.users.updateOne({n:"A"}, { $pull: {tags: "x"} })

# $pop remove first (-1) or last (1) element
db.users.updateOne({n:"A"}, { $pop: {tags: 1} })

# update an array element by position
db.users.updateOne({}, { $set: {"tags.0": "first"} })
db.users.updateOne({"tags":"old"}, { $set: {"tags.$":"new"} })
03

ドキュメントのクエリ

比較演算子

比較演算子はクエリの土台です。$in は同じフィールドへの複数の $or 条件よりはるかに効率的です。1 つのフィールドに複数の演算子を組み合わせられます(範囲なら $gte と $lte)。$exists:true はフィールドが存在するドキュメントを、$exists:false は存在しないドキュメントを見つけます。

mongodb
# $eq equal (same as direct value)
db.products.find({ price: { $eq: 100 } })

# $ne not equal
db.products.find({ price: { $ne: 100 } })

# $gt, $gte, $lt, $lte
db.products.find({ price: { $gte: 50, $lte: 200 } })

# $in matches any value in an array
db.products.find({ category: { $in: ["books", "music"] } })

# $nin not in array
db.products.find({ category: { $nin: ["books"] } })

# $exists check field presence
db.products.find({ discount: { $exists: true } })

論理演算子

暗黙の AND(フィルター内のカンマ)が最も一般的で効率的です。明示的な $and が必要なのは、同じフィールドに複数の条件を付けるときだけです(同じフィールドへの暗黙の AND は前の条件を上書きします)。$or は個別のインデックススキャンと結果のマージを行うため、パフォーマンスのため $or 内のフィールドにはインデックスを付けましょう。

mongodb
# $and (explicit, useful for same-field conditions)
db.users.find({ $and: [
  { age: { $gte: 18 } },
  { age: { $lte: 65 } }
]})

# $or matches if ANY condition is true
db.users.find({ $or: [
  { status: "active" },
  { vip: true }
]})

# $nor matches if NO condition is true
db.users.find({ $nor: [{ status: "active" }]})

# $not inverts a condition
db.users.find({ age: { $not: { $gt: 18 } } })

# implicit AND (comma-separated)
db.users.find({ age: { $gte: 18 }, status: "active" })

要素・評価演算子

$type は BSON 型でフィルタリングします(型が混在するフィールドに便利)。$regex は 'i'(大文字小文字を無視)などのオプションをサポートしますが、前方アンカーのない正規表現はインデックスを効率的に使えません。$expr を使うと通常の演算子では不可能なフィールド間の比較ができますが、インデックスを迂回することがあるので控えめに使いましょう。

mongodb
# $type filter by BSON data type
db.users.find({ age: { $type: "int" } })
db.users.find({ age: { $type: ["int", "double"] } })

# $regex regular expression match
db.users.find({ name: { $regex: "^Al", $options: "i" } })

# $mod modulo operation
db.users.find({ age: { $mod: [2, 0] } })  # even ages

# $expr compare fields within a document
db.orders.find({ $expr: { $gt: ["$total", "$budget"] } })

# $jsonSchema validate against a schema
db.users.find({ $jsonSchema: {
  required: ["name", "email"]
}})

配列クエリ演算子

$all は指定した値をすべて含む配列を見つけます(順序は問わない)。$elemMatch は 1 つの配列要素が複数の条件を同時に満たす必要があるときに不可欠です(素のクエリでは要素ごとに個別にマッチしてしまいます)。$size は完全一致の長さだけに対応し範囲指定はできません — あらかじめ長さを計算して別フィールドに保存しておきましょう。

mongodb
# $all: array contains ALL specified values
db.posts.find({ tags: { $all: ["mongo", "db"] } })

# $elemMatch: at least one element matches all conditions
db.students.find({ scores: { $elemMatch: {
  subject: "math", score: { $gte: 90 }
}}})

# $size: array of exact length
db.users.find({ tags: { $size: 3 } })

# match if array contains the value
db.posts.find({ tags: "mongo" })

# match a specific array index
db.users.find({ "scores.0": 95 })  # first score is 95

カーソルメソッドとソート

skip+limit でページネーションを実装できますが、オフセットが大きくなると skip は遅くなります(スキップした分も全部スキャンするため)。深いページネーションには keyset ページネーションを使いましょう: ソートフィールドが最後に見た値より大きいというフィルターでクエリします。sort() はインデックスを使えばメモリ内ソートを避けられます — 大きなコレクションではソートフィールドに必ずインデックスを付けましょう。

mongodb
# limit and skip (pagination)
db.users.find().limit(10)
db.users.find().skip(20).limit(10)  # page 3

# sort: 1 ascending, -1 descending
db.users.find().sort({ age: 1, name: -1 })

# count results
db.users.find({active:true}).count()

# iterate the cursor in the shell
db.users.find().forEach(doc => print(doc.name))

# get a specific field's distinct values
db.users.distinct("city")
04

インデックス

インデックスの作成

インデックスはクエリを劇的に速くしますが、書き込みを遅くしディスクも消費します。単一フィールドのインデックスはそのフィールドへのクエリをどちらのソート方向でもサポートします。複合インデックスは ESR(Equality、Sort、Range)ルールに従ってフィールド順を決めるのが最適です。TTL インデックスは一定期間後にドキュメントを自動削除します — セッションやログに最適です。

mongodb
# create a single-field index
db.users.createIndex({ email: 1 })          # ascending
db.users.createIndex({ age: -1 })            # descending

# create a unique index
db.users.createIndex({ email: 1 }, { unique: true })

# create a compound index
db.users.createIndex({ lastName: 1, firstName: 1 })

# create a text index
db.posts.createIndex({ title: "text", body: "text" })

# create a TTL (time-to-live) index
db.sessions.createIndex({ createdAt: 1 },
  { expireAfterSeconds: 3600 })

# name an index explicitly
db.users.createIndex({ email: 1 }, { name: "email_idx" })

インデックスの確認と管理

getIndexes はすべてのインデックスをキーとオプション付きで一覧表示します。hideIndex/unhideIndex を使うとインデックスを実際に削除せずに「削除した場合の影響」を試せます — クエリプランナーは非表示のインデックスを無視します。性能が変わらなければ削除しても安全です。インデックスを変更するときは必ず前後で explain() を実行しましょう。

mongodb
# list all indexes on a collection
db.users.getIndexes()

# total index size in bytes
db.users.totalIndexSize()

# drop an index by name
db.users.dropIndex("email_1")

# drop all indexes except _id
db.users.dropIndexes()

# hide an index (test impact before dropping)
db.users.hideIndex("email_1")
db.users.unhideIndex("email_1")

# check if queries use indexes
db.users.find({email:"[email protected]"}).explain("executionStats")

特殊なインデックス

2dsphere インデックスは地理クエリ($near、$geoWithin)を支えます。Hashed インデックスはハッシュベースのシャーディングでデータを均等に分散します。ワイルドカードインデックス($**)は予測できない/可変のフィールド名をカバーします — ポリモーフィックなデータに便利です。部分インデックスは条件に一致するドキュメントだけをインデックス化するので、一部だけクエリする場合はディスクを節約できます。

mongodb
# geospatial 2dsphere index (GeoJSON points)
db.places.createIndex({ location: "2dsphere" })
db.places.find({
  location: { $near: {
    $geometry: { type: "Point", coordinates: [-73.99, 40.73] },
    $maxDistance: 1000
  }}
})

# hashed index (for sharding)
db.users.createIndex({ user_id: "hashed" })

# wildcard index (index arbitrary field names)
db.products.createIndex({ "$**": 1 })

# partial index (only matching documents)
db.users.createIndex({ email: 1 },
  { partialFilterExpression: { active: true } })

explain とクエリプラン

explain() はパフォーマンスチューニングの主役です。COLLSCAN(コレクションスキャン)はインデックスが使われていないことを意味し、大きなコレクションでは危険信号です。IXSCAN はインデックスが使われたことを意味します。totalDocsExamined >> nReturned ならインデックスが貧弱です(少数を返すのに大量のドキュメントを調べている)。hint() で特定のインデックスを強制し、プランナーの選択を検証できます。

mongodb
# explain a query (basic)
db.users.find({age:30}).explain()

# explain with execution stats (timing)
db.users.find({age:30}).explain("executionStats")

# key fields in the output:
#   winningPlan.stage    -> COLLSCAN (bad) or IXSCAN (good)
#   totalDocsExamined    -> should be close to nReturned
#   executionTimeMillis  -> query duration
#   indexUsed            -> which index was chosen

# force a specific index (testing)
db.users.find({age:30}).hint("age_1")
db.users.find({age:30}).hint({age:1})

インデックスのベストプラクティス

ESR(Equality、Sort、Range)ルールは複合インデックス設計の最重要原則です: 等価フィルターのフィールドを先に、次にソートフィールド、最後に範囲フィールドを置きます。カバードクエリ(必要な全フィールドがインデックスに含まれる)はドキュメントをフェッチせず、最速のクエリになります。使わないインデックスは避けましょう — 1 つごとに書き込みのオーバーヘッドが増えます。

mongodb
# ESR rule: Equality, Sort, Range for compound indexes
# equality fields first, then sort, then range
db.orders.createIndex({
  status: 1,        # Equality  (filter)
  date: 1,          # Sort      (order)
  amount: 1         # Range     (comparison)
})

# avoid over-indexing: each index slows writes
db.orders.getIndexes().length

# covered query: index satisfies query without fetching doc
db.users.createIndex({ name: 1, email: 1 })
db.users.find({ name: "A" }, { _id: 0, name: 1, email: 1 })

# background index build (deprecated in 4.2+, builds don't block)
db.users.createIndex({ name: 1 })  # non-blocking by default
05

アグリゲーション

アグリゲーションパイプラインの基本

アグリゲーションパイプラインはドキュメントをステージごとに順番に処理します。パイプラインの早い段階に $match を置くと処理対象が減り(インデックスも使えます)、$group は SQL の GROUP BY に相当します。$count は $group + $project のショートカットです。順序が重要です: 先にフィルターし、次にグループ化、その後ソート、最後に limit です。

mongodb
# a pipeline is an array of stages
db.orders.aggregate([
  { $match: { status: "shipped" } },
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } },
  { $limit: 10 }
])

# each stage transforms documents and passes them
# to the next stage

# count documents
db.orders.aggregate([
  { $match: { status: "shipped" } },
  { $count: "shippedCount" }
])

$match、$project、$limit

$match は必ずできるだけ早く置きましょう — 後続の全ステージの処理対象が減り、インデックスも使えます。$project はドキュメントを整形し、式で新しいフィールドを計算します。$group の前に $project でフィールドのリネームや計算をしておくのはよくあるパターンです。$unset はフィールドを除外するショートハンドです。

mongodb
# $match filters documents (like find)
{ $match: { status: "active", age: { $gte: 18 } } }

# $project reshapes documents (1 include, 0 exclude)
{ $project: { name: 1, _id: 0, "address.city": 1 } }

# $project with computed fields
{ $project: {
  fullName: { $concat: ["$first", " ", "$last"] },
  ageNextYear: { $add: ["$age", 1] }
}}

# $limit and $skip
{ $limit: 10 }
{ $skip: 20 }

# $unset removes fields (inverse of $project)
{ $unset: "tempField" }

$group とアキュムレータ

$group はアグリゲーションの核となるステージです。_id がグルーピングキーで(null にすると全ドキュメントを集計)、$push はグループごとの値の配列を作り、$addToSet は重複を排除します。$first/$last はグループ内のドキュメント順に依存するので、順序が重要なら $group の前に $sort しましょう。メモリ上限はステージごとに 100MB です(大きなデータセットには allowDiskUse を使う)。

mongodb
# $group: group by a field and aggregate
{ $group: {
  _id: "$category",
  count: { $sum: 1 },
  totalRevenue: { $sum: "$amount" },
  avgPrice: { $avg: "$price" },
  minPrice: { $min: "$price" },
  maxPrice: { $max: "$price" },
  products: { $push: "$name" },     # array of values
  firstOrder: { $first: "$date" },
  lastOrder: { $last: "$date" }
}}

# group by multiple fields
{ $group: { _id: { category: "$cat", status: "$status" } } }

# group ALL documents together (_id: null)
{ $group: { _id: null, total: { $sum: "$amount" } } }

$lookup(結合)

$lookup は左外部結合(SQL の LEFT JOIN に相当)を行います。結合したデータは 'as' で名付けた配列フィールドに入ります。pipeline 形式を使うと結合先のドキュメントをフィルタリング・変換できます。$unwind は配列フィールドを分解し(要素ごとに出力ドキュメントが 1 つ)、$lookup の後で結果をフラット化するためによく使われます。MongoDB では結合は埋め込みデータより非効率です。

mongodb
# $lookup: join another collection (left outer join)
{ $lookup: {
  from: "orders",
  localField: "_id",
  foreignField: "customerId",
  as: "orders"
}}

# with pipeline (filtered/transformed join)
{ $lookup: {
  from: "orders",
  let: { custId: "$_id" },
  pipeline: [
    { $match: { $expr: { $eq: ["$customerId", "$$custId"] } } },
    { $project: { amount: 1, _id: 0 } }
  ],
  as: "recentOrders"
}}

# $unwind: flatten an array field into multiple docs
{ $unwind: "$orders" }

$unwind、$sort、$facet

$facet は同じ入力に対して複数のサブパイプラインを実行します — top N、件数、内訳など複数の集計を 1 クエリで得たいダッシュボードに最適です。$bucket は値を範囲に自動分類します。$unwind に preserveNullAndEmptyArrays を付けると、配列が空や存在しないドキュメントも保持します — パイプラインでのデータ消失を避けられます。

mongodb
# $unwind with preserveNullAndEmptyArrays
{ $unwind: {
  path: "$tags",
  preserveNullAndEmptyArrays: true
}}

# $sort within pipeline
{ $sort: { total: -1 } }

# $facet: run multiple pipelines in parallel
{ $facet: {
  "topCustomers": [{ $sort: {total:-1} }, { $limit: 5 }],
  "byCategory":   [{ $group: { _id: "$cat" } }],
  "totalCount":   [{ $count: "n" }]
}}

# $bucket: group into ranges automatically
{ $bucket: {
  groupBy: "$price",
  boundaries: [0, 50, 100, 500],
  default: "other",
  output: { count: { $sum: 1 } }
}}
07

トランザクション

ACID トランザクション

マルチドキュメントトランザクションはコレクションをまたぐ ACID 保証を提供します(レプリカセットかシャーディングクラスタが必要)。トランザクション内のすべての操作にセッションを渡します。commitTransaction で変更が確定して可視化され、abortTransaction で全変更がロールバックされます。トランザクションは短く保ちましょう — ロックを保持し性能に影響します。

mongodb
# multi-document transaction (replica set required)
const session = db.getMongo().startSession()
session.startTransaction()

try {
  db.accounts.updateOne(
    { name: "Alice" }, { $inc: { balance: -100 } }, { session }
  )
  db.accounts.updateOne(
    { name: "Bob" }, { $inc: { balance: 100 } }, { session }
  )
  session.commitTransaction()
} catch (e) {
  session.abortTransaction()
  print("Transaction aborted: " + e)
} finally {
  session.endSession()
}

トランザクションの Read/Write Concern

Read concern は読み取りの「新しさ」と一貫性を制御します。'snapshot' はシャードをまたいでトランザクション的に一貫したビューを提供し、レポーティングに理想的です。Write concern は耐久性を制御します: w:majority は確認応答の前にデータが複製されることを保証し(プライマリのフェイルオーバーでも消失しません)、j:true はジャーナルのディスクフラッシュを待ちます。高い concern は安全ですが遅くなります。

mongodb
# set transaction-level read/write concern
session.startTransaction({
  readConcern: { level: "snapshot" },
  writeConcern: { w: "majority", j: true, wtimeout: 5000 }
})

# read concern levels:
#   "local"      - sees latest local data (default)
#   "majority"   - committed, replicated to majority
#   "snapshot"   - consistent snapshot across shards

# write concern levels:
#   { w: 1 }             - ack from primary (default)
#   { w: "majority" }    - ack from majority of members
#   { j: true }          - wait for journal write

リトライとエラー

MongoDB はリトライ可能なエラーに errorLabels を付けます: TransientTransactionError(トランザクション全体を再試行)と UnknownCommitResult(commit だけ再試行)。本番のドライバには組み込みのリトライがあります。トランザクションは可能な限り冪等に設計しましょう。ロックを長時間保持して他の操作をブロックする長時間トランザクションは避けてください。

mongodb
# transactions can fail with TransientTransactionError
# retry the whole transaction on these errors

function runTransaction(txnFunc) {
  while (true) {
    const session = db.getMongo().startSession()
    try {
      session.startTransaction()
      txnFunc(session)
      session.commitTransaction()
      return
    } catch (e) {
      session.abortTransaction()
      if (e.errorLabels &&
          e.errorLabels.includes("TransientTransactionError")) {
        continue  // retry
      }
      throw e   // non-retryable error
    } finally {
      session.endSession()
    }
  }
}

単一ドキュメントのアトミック操作

単一ドキュメントへの操作はデフォルトでアトミックです — トランザクションは不要です。findOneAndUpdate/findOneAndReplace/findOneAndDelete はドキュメントをアトミックに返します(連番 ID の生成に最適)。多くのワークロードでは、関連データを 1 つのドキュメントに埋め込み、アトミックな演算子($inc、$push)を使えばマルチドキュメントトランザクション自体が不要になります。

mongodb
# single-document operations are ALWAYS atomic
db.counters.updateOne(
  { _id: "pageViews" },
  { $inc: { count: 1 } }
)

# findAndModify: atomically find & update, return the doc
db.sequences.findOneAndUpdate(
  { _id: "orderId" },
  { $inc: { seq: 1 } },
  { returnNewDocument: true }
)

# atomic upsert (create-or-increment)
db.counters.updateOne(
  { _id: "visits", date: "2025-01-01" },
  { $inc: { count: 1 } },
  { upsert: true }
)

# use $expr for conditional atomic updates
db.products.updateMany(
  { $expr: { $lt: ["$stock", "$reorderLevel"] } },
  { $set: { needsRestock: true } }
)

Two-Phase Commit(パターン)

Two-Phase Commit パターンは、ネイティブなマルチドキュメントトランザクションなしで分散トランザクションを模倣する手法です。'pending' 状態を記録しておくことで、移行中にクラッシュしても復旧プロセスが再開またはロールバックできます。利用できるならネイティブトランザクションを使いましょう — このパターンは複雑でミスを起こしやすく、主に教育目的とレガシー用途のためのものです。

mongodb
# pattern for atomic transfers without transactions
# (pre-4.0 compatibility, or cross-system transfers)

# 1. create a pending transaction document
db.transactions.insertOne({
  _id: "t1", from: "Alice", to: "Bob", amount: 100, state: "pending"
})

# 2. debit source
db.accounts.updateOne(
  { name: "Alice", pendingTransactions: { $ne: "t1" } },
  { $inc: { balance: -100 }, $push: { pendingTransactions: "t1" } }
)

# 3. credit destination
db.accounts.updateOne(
  { name: "Bob", pendingTransactions: { $ne: "t1" } },
  { $inc: { balance: 100 }, $push: { pendingTransactions: "t1" } }
)

# 4. mark transaction done
db.transactions.updateOne({ _id: "t1" }, { $set: { state: "done" } })

# 5. clean up pending references
db.accounts.updateMany({},
  { $pull: { pendingTransactions: "t1" } })
08

データモデリング

埋め込み vs 参照

MongoDB モデリング最大の判断です: 一緒に読まれ、めったに変わらないデータは埋め込み(embed)。大きい、共有される、独立して更新されるデータは参照(reference)。1 対 1 の排他的な関係(ユーザーの住所など)なら埋め込み、データが再利用される(多くの注文に現れる商品)か無制限に増える(ユーザーの数百万件のログ)なら参照しましょう。

mongodb
# EMBED: store related data in one document
db.users.insertOne({
  name: "Alice",
  addresses: [
    { city: "NYC", zip: "10001" },
    { city: "LA", zip: "90001" }
  ]
})
# Pros: single read, atomic update
# Cons: document size limit (16MB), data duplication

# REFERENCE: store IDs, join with $lookup
db.users.insertOne({ name: "Alice" })
db.orders.insertOne({
  customerId: ObjectId("..."),
  amount: 100
})
# Pros: no duplication, independent updates
# Cons: needs joins, more queries

1 対多のリレーション

'少数' の関係なら埋め込みです。'多数' なら子側から参照します(各子に親の ID)。'非常に多数'(数百万件)ならバケットパターンを使いましょう: 子ドキュメントを親が所有するバケット(例: 月ごと)にまとめ、ドキュメントサイズとクエリ速度のバランスを取ります。これで無制限に伸びる配列も過剰な子ドキュメントも避けられます。

mongodb
# FEW: embed (e.g., a few addresses per user)
db.users.insertOne({
  name: "Alice",
  addresses: [{ city: "NYC" }, { city: "LA" }]
})

# MANY: reference with parent pointer
db.posts.insertOne({ title: "Hello", authorId: ObjectId("...") })

# VERY MANY: reference from parent (bucket pattern)
db.users.updateOne(
  { _id: userId },
  { $push: { postIds: postId } }   # beware 16MB limit
)

# BUCKET pattern for time series (thousands of items)
db.buckets.insertOne({
  ownerId: userId,
  date: "2025-01",
  measurements: [ {t: 1, v: 30}, {t: 2, v: 31} ]
})

多対多のリレーション

多対多はクエリパターンとデータ量で方式を選びます。両側配列は速いですが二重管理が必要です。中間コレクション(マッピングテーブル)が最も柔軟でスケールします — 関係のメタデータ(受講日、成績など)も保存でき、親ドキュメントの肥大化を避けられます。

mongodb
# option 1: arrays of ObjectIds on both sides
db.students.insertOne({ name: "Alice", courseIds: [c1, c2] })
db.courses.insertOne({ name: "Math", studentIds: [s1, s2] })

# option 2: one side references (smaller side)
db.students.insertOne({ name: "Alice", courseIds: [c1, c2] })

# option 3: mapping/junction collection
db.enrollments.insertOne({
  studentId: s1,
  courseId: c1,
  enrolledAt: ISODate(),
  grade: "A"
})

# query: find a student's courses
db.enrollments.find({ studentId: s1 })

スキーマ設計パターン

Attribute Pattern は属性が異なるエンティティ(スペックの違う商品)を扱います — スパースなフィールドを避け、動的な属性に対応できます。Polymorphic Pattern は似ていても形の違うデータを、type 判別子付きで 1 つのコレクションに保存します。Outlier Pattern は例外的なドキュメント(数百万フォロワーのセレブ)を、埋め込みではなく参照で扱います。

mongodb
# ATTRIBUTE PATTERN: flexible attributes (e.g., products)
db.products.insertOne({
  name: "Laptop",
  attributes: [
    { k: "cpu", v: "i7" },
    { k: "ram", v: 16 }
  ]
})
# query: db.products.find({ "attributes.k": "cpu", "attributes.v": "i7" })

# POLYMORPHIC PATTERN: one collection, type discriminator
db.events.insertMany([
  { type: "click", url: "/home", userId: 1 },
  { type: "purchase", orderId: 99, total: 50 }
])

# OUTLIER PATTERN: cap large lists
db.users.updateOne({n:"A"}, { $set: { reviews: "see reviews collection" } })

スキーマバリデーション

スキーマバリデーションは書き込み時にドキュメントの構造を強制します — 固定スキーマへの MongoDB 流の答えです。validationLevel の 'strict' はすべての書き込みを検証し、'moderate' は insert とフルアップデートだけ検証します。validationAction の 'error' は無効なドキュメントを拒否し、'warn' はログに残して受け入れます。バリデーションはアプリレベルの検証を補完するもので(置き換えではなく)、併用しましょう。

mongodb
# add a JSON schema validator to a collection
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        name: { bsonType: "string", maxLength: 100 },
        email: { bsonType: "string", pattern: "^\S+@\S+$" },
        age: { bsonType: "int", minimum: 0, maximum: 150 },
        role: { enum: ["admin", "user", "guest"] }
      }
    }
  },
  validationLevel: "strict",
  validationAction: "error"
})

# add validation to an existing collection
db.runCommand({ collMod: "users", validator: { ... } })

# check existing validation rules
db.getCollectionInfos({ name: "users" })
09

レプリカセット

レプリカセットの基本

レプリカセットは高可用性と読み取りスケールを提供します。プライマリ(書き込みを受け付ける)は 1 メンバーだけで、他は非同期に複製します。プライマリが落ちると選挙でセカンダリが自動昇格します。投票メンバー数は奇数(最低 3)にすると選挙の同票を避けられます。rs.status() で各メンバーの健康状態、状態、レプリケーションラグが見られます。

mongodb
# a replica set = 1 primary + N secondaries
# all writes go to the primary; secondaries replicate

# initiate a replica set
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "host1:27017" },
    { _id: 1, host: "host2:27017" },
    { _id: 2, host: "host3:27017" }
  ]
})

# check replica set status
rs.status()
rs.conf()

# step down the primary (force an election)
rs.stepDown(60)

# add a new member
rs.add("host4:27017")
rs.remove("host4:27017")

Read Preference

Read preference は一貫性と負荷のバランスを取ります。primary は常に最新の書き込みを読めることを保証します。secondary/secondaryPreferred はプライマリから読み取りを offload しますが、データが古い可能性があります(レプリケーションラグは通常ミリ秒程度)。nearest はレイテンシを最小化し、地理的に分散したアプリに理想的です。分析・レポーティング系のワークロードは secondary 読み取りを使いましょう。

mongodb
# control where reads are routed
# primary (default) - always read from primary (strongest consistency)
db.users.find().readPref("primary")

# primaryPreferred - primary if available, else secondary
db.users.find().readPref("primaryPreferred")

# secondary - only secondaries (may be stale)
db.users.find().readPref("secondary")

# secondaryPreferred - prefer secondaries to offload primary
db.users.find().readPref("secondaryPreferred")

# nearest - lowest latency member
db.users.find().readPref("nearest")

# set in connection string
mongodb://host1:27017/mydb?replicaSet=rs0&readPreference=secondary

Write Concern

Write concern は速度と安全性をトレードオフします。w:1 はプライマリが書いた時点で ack します(速いが、複製前にプライマリが落ちるとデータを失う可能性)。w:majority は書き込みが複製されることを保証し、単一ノード障害に耐えます(重要なデータには推奨)。j:true はディスク上のジャーナルフラッシュを待ちます。クラスタレベルで合理的なデフォルトを設定しましょう。

mongodb
# control how durable a write must be before ack
# w: 1 - primary acks (default, fastest, least safe)
db.users.insertOne(doc, { writeConcern: { w: 1 } })

# w: "majority" - majority of members confirmed
db.users.insertOne(doc, { writeConcern: { w: "majority" } })

# j: true - wait for journal flush (survives crash)
db.users.insertOne(doc, { writeConcern: { w: 1, j: true } })

# wtimeout - max wait time in ms
db.users.insertOne(doc, {
  writeConcern: { w: "majority", wtimeout: 5000 }
})

# set default write concern for the cluster
db.adminCommand({
  setDefaultRWConcern: { defaultWriteConcern: { w: "majority" } }
})

アービタと選挙

Arbiter はデータを保持せず投票権だけを提供します — 2 ノード構成で多数決を作るのに便利ですが、3 つ目のデータノードの方が望ましいです。Priority 0 のメンバーは決してプライマリになれません(分析専用や DR ノード向き)。Hidden メンバーは read preference 'nearest' の対象から外れ、バックアップに理想的です。Delayed メンバーは遅れて複製するため、誤削除からの復旧が可能です。

mongodb
# an arbiter votes in elections but holds no data
rs.addArb("host5:27017")

# useful to break ties in even-member sets (e.g., 2 data + 1 arbiter)
# but prefer 3 data members for durability

# force a member to never become primary (priority 0)
rs.conf().members[1].priority = 0
rs.reconfig(rs.conf())

# hidden member: not visible to clients, used for analytics/backup
rs.conf().members[2].hidden = true
rs.conf().members[2].priority = 0
rs.reconfig(rs.conf())

# delayed member: lags behind (insurance against human errors)
rs.conf().members[3].secondaryDelaySecs = 3600
rs.conf().members[3].priority = 0

Oplog とレプリケーションの仕組み

oplog(operation log)はすべての書き込みを記録する capped コレクションで、セカンダリはこれを順に適用して複製します。セカンダリが oplog ウィンドウを超えて遅れるとフル再同期が必要です。printReplicationInfo は oplog の時間幅を、printSecondaryReplicationInfo は各セカンダリのラグを表示します。oplog を大きくすると、より長いダウンタイムに耐えられます。

mongodb
# the oplog is a capped collection of all writes
use local
db.oplog.rs.stats()
db.oplog.rs.find().sort({ $natural: -1 }).limit(5)

# each oplog entry is an idempotent operation
# { ts: ..., op: "i", ns: "mydb.users", o: { ... } }

# check replication lag
rs.printReplicationInfo()   # primary's oplog window
rs.printSecondaryReplicationInfo()  # each secondary's lag

# resync a stale secondary (full re-sync)
rs.syncFrom("host2:27017")

# change the oplog size (MongoDB 4.4+)
db.adminCommand({ replSetResizeOplog: 1, size: 16384 })  # MB
10

シャーディング

シャーディングの基本

シャーディングはコレクションを複数のシャードに水平分割してスケールさせる仕組みです。シャードキーがデータの分散を決め、シャーディング後は変更できません。Hashed シャーディングは均等に分散し(ObjectId のような単調増加キー向き)、範囲シャーディングは対象を絞ったクエリに有利ですがホットスポットが生じることがあります。シャードキーは慎重に選びましょう — 後から簡単に変えられません。

mongodb
# sharding distributes data across multiple machines
# requires: config servers + shard replica sets + mongos router

# enable sharding on a database
sh.enableSharding("mydb")

# shard a collection (index on shard key required first)
sh.shardCollection("mydb.users", { userId: 1 })

# hash-based sharding (even distribution)
db.users.createIndex({ userId: "hashed" })
sh.shardCollection("mydb.users", { userId: "hashed" })

# view shard status
sh.status()
sh.addShard("rs1/host1:27017,host2:27017")

# balancer moves chunks between shards automatically
sh.startBalancer()
sh.stopBalancer()

シャードキーの選択

シャードキーはシャーディングで最も重要な決定です。よく使うクエリをサポートしている必要があります(シャードキーを含まないクエリは全シャードに散らばります — scatter-gather)。カーディナリティが高いと移動不能な jumbo chunk を防げます。単調増加するキー(タイムスタンプ、ObjectId)は書き込みが 1 つのシャードに集中するため、Hashed シャーディングを使いましょう。複合キーは最も選択的なフィールドを先頭にします。

mongodb
# GOOD shard key properties:
# - high cardinality (many distinct values)
# - low frequency (no single value dominates)
# - non-monotonic (avoids hot shards) OR use hashed

# hashed shard key (even distribution)
sh.shardCollection("mydb.logs", { _id: "hashed" })

# ranged shard key (enables targeted queries)
sh.shardCollection("mydb.events", { region: 1, date: 1 })

# compound shard key
sh.shardCollection("mydb.orders", { customerId: 1, orderId: 1 })

# check chunk distribution
db.getSiblingDB("config").chunks.find({ ns: "mydb.users" })

# see data distribution per shard
db.users.getShardDistribution()

ゾーンとタグ対応シャーディング

ゾーン(tag-aware sharding)は特定のデータ範囲を特定のシャードに振り分けます — データ所在地の法令対応(GDPR は EU データを EU 内に要求)、地理的な局所性(リージョン内の高速読み取り)、ハードウェアの階層化(ホットデータは SSD、コールドは HDD)に使えます。バランサーはチャンク移動時にゾーン範囲を尊重します。まずシャードタグを定義し、次に範囲にタグを付けます。

mongodb
# tag shards by region (data locality / compliance)
sh.addShardTag("shard-us-east", "US")
sh.addShardTag("shard-eu", "EU")

# associate a key range with a tag
sh.addTagRange(
  "mydb.users",
  { region: "US", _id: MinKey },
  { region: "US", _id: MaxKey },
  "US"
)
sh.addTagRange(
  "mydb.users",
  { region: "EU", _id: MinKey },
  { region: "EU", _id: MaxKey },
  "EU"
)

# the balancer migrates tagged data to tagged shards
# useful for data residency (GDPR) and geo-locality

チャンク管理

チャンクはシャード間でデータを移動する単位です。バランサーがチャンクの分割と移行を自動で行い、シャードの均衡を保ちます。Jumbo chunk はサイズ上限を超えて移行できないチャンクで、良いシャードキーのカーディナリティで避けましょう。デフォルトの 128MB は移行速度とオーバーヘッドのバランスです。手動のチャンク操作はトラブルシューティング用で、日常的に使うものではありません。

mongodb
# chunks are ranges of shard key values
# default chunk size: 128MB (configurable)

# view chunks for a collection
db.getSiblingDB("config").chunks.find({ ns: "mydb.users" })

# manually move a chunk (testing)
sh.moveChunk("mydb.users", { userId: 100 }, "shard2")

# split a chunk at a specific value
sh.splitAt("mydb.users", { userId: 1000 })

# merge contiguous chunks
sh.mergeChunks("mydb.users",
  { userId: MinKey },
  { userId: 1000 }
)

# find chunks too large to migrate (jumbo chunks)
sh.status(true)   # verbose

シャーディングクラスタの構成要素

シャーディングクラスタは 3 つの構成要素からなります: config サーバー(メタデータ、レプリカセットとしてデプロイ)、mongos ルーター(ステートレスなクエリルーターでクライアントが接続する先)、シャード(それぞれがデータの一部を持つレプリカセット)。クライアントはシャードに直接接続しません。シャードを削除すると残りのシャードへのデータ移行が始まります — 時間がかかるので監視しましょう。

mongodb
# config servers store metadata and routing info
# (deploy as a 3-member replica set)
# config server connection string:
# mongodb://cfg1:27019,cfg2:27019,cfg3:27019/config?replicaSet=cfgRS

# mongos is the query router (stateless, scale horizontally)
# clients connect to mongos, not shards directly
mongos --configdb cfgRS/cfg1:27019,cfg2:27019,cfg3:27019

# each shard is a replica set
sh.addShard("shardRS1/s1a:27017,s1b:27017,s1c:27017")
sh.addShard("shardRS2/s2a:27017,s2b:27017,s2c:27017")

# check cluster status
sh.status()

# remove a shard (migrates its data first)
db.adminCommand({ removeShard: "shardRS2" })
11

セキュリティと認証

認証とユーザー

認証は本人確認です。auth を有効にする前に admin ユーザーを作らないと締め出されます。組み込みロールは読み取り専用からフル管理者まで揃っています。シェルでは passwordPrompt() を使うと履歴に平文パスワードが残りません。ユーザーはデータベース単位でスコープされますが、他のデータベースへのロールも持てます。本番では TLS を有効にしましょう(net.tls.mode)。

mongodb
# enable auth: start mongod with --auth
# or set security.authorization: "enabled" in config

# create the first admin user (before enabling auth)
use admin
db.createUser({
  user: "admin",
  pwd: passwordPrompt(),   // prompts securely
  roles: [ { role: "userAdminAnyDatabase", db: "admin" },
           { role: "readWriteAnyDatabase", db: "admin" } ]
})

# create a user for a specific database
use mydb
db.createUser({
  user: "appUser",
  pwd: passwordPrompt(),
  roles: [ { role: "readWrite", db: "mydb" } ]
})

# authenticate as a user
db.auth("appUser", "password")

組み込みロールとカスタムロール

組み込みロールは一般的なケースをカバーし、カスタムロールは最小権限を実現します。特権はリソース(データベース/コレクション)と許可するアクション(find、insert、update など)のペアです。必要最小限だけ付与しましょう — レポーティング用ユーザーなら特定コレクションへの 'find' だけで足ります。カスタムロールは admin データベースに保存され、複数ユーザーで再利用できます。

mongodb
# built-in roles:
#   read, readWrite, dbAdmin, dbOwner, userAdmin  (per database)
#   readAnyDatabase, readWriteAnyDatabase,         (all databases)
#   userAdminAnyDatabase, dbAdminAnyDatabase
#   root (superuser), clusterAdmin, backup, restore

# create a custom role with fine-grained privileges
db.createRole({
  role: "analyst",
  privileges: [
    { resource: { db: "mydb", collection: "reports" },
      actions: ["find"] },
    { resource: { db: "mydb", collection: "" },
      actions: ["listCollections"] }
  ],
  roles: []
})

# grant a role to a user
db.grantRolesToUser("appUser", [{ role: "analyst", db: "mydb" }])
db.revokeRolesFromUser("appUser", [{ role: "analyst", db: "mydb" }])

TLS/SSL 暗号化

TLS は通信中のデータを暗号化します — 本番では必須です。requireTLS は非 TLS 接続を拒否します。内部 PKI なら x.509 証明書認証を使えます(パスワード不要 — 証明書そのものが資格情報)。$external データベースが x.509 ユーザーを保存します。本番では必ず正規の CA(または内部 CA)を使い、自己署名証明書はテスト専用にしましょう。

mongodb
# enable TLS in mongod.conf
net:
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/mongodb/server.pem
    CAFile: /etc/mongodb/ca.pem

# connect with TLS and verify the server cert
mongosh "mongodb://host:27017/mydb" \
  --tls --tlsCAFile /etc/mongodb/ca.pem

# connect with a client certificate (x.509 auth)
mongosh "mongodb://host:27017/mydb" \
  --tls --tlsCertificateKeyFile client.pem \
  --tlsCAFile ca.pem \
  --authenticationMechanism MONGODB-X509 \
  --authenticationDatabase '$external'

# generate a self-signed cert for testing
openssl req -x509 -newkey rsa:4096 -nodes \
  -keyout server.key -out server.crt -days 365

ネットワークと監査

bindIp は MongoDB が待ち受けるネットワークインターフェースを制限します — MongoDB をインターネットに直接晒してはいけません(bindIp: 0.0.0.0 +認証なしは無数の流出事故を引き起こしてきました)。監査(Enterprise のみ)はコンプライアンスのためセキュリティ関連の操作を記録します。Community エディションでは OS レベルのツール(auditd)やアプリレベルのログが代替になります。

mongodb
# restrict network interface in mongod.conf
net:
  bindIp: 127.0.0.1,10.0.0.5    # never 0.0.0.0 in production
  port: 27017

# enable auditing (enterprise feature)
auditLog:
  destination: file
  format: JSON
  path: /var/log/mongodb/audit.log
  filter: '{ atype: { $in: ["authenticate","createCollection","dropDatabase"] } }'

# view current authentication mechanisms
db.runCommand({ getCmdLineOpts: 1 })

# enable FIPS mode (government compliance)
setParameter:
  fipsMode: true

フィールドレベル暗号化(CSFLE)

CSFLE は機密フィールドをクライアント側で暗号化するため、サーバー・バックアップ・ログに平文が一切残りません — 最も強力なデータ保護です。Deterministic 暗号化は等価クエリに対応し、Random 暗号化はより安全ですが検索できません。自動暗号化(ドライバのスキーマ経由)はアプリコードに対して透過的です。暗号化キーは KMS(AWS KMS、ローカルキーなど)で管理します。

mongodb
# Client-Side Field Level Encryption encrypts fields
# before sending to the server — server never sees plaintext

# define a data key in the key vault
const clientEncryption = db.getMongo().getClientEncryption()
const keyId = clientEncryption.createDataKey(
  "local", { keyAltNames: ["mainKey"] }
)

# encrypt a field explicitly
const ssn = clientEncryption.encrypt(
  keyId, "123-45-6789", "deterministic"
)

# store encrypted, query with encrypted value
db.patients.insertOne({ name: "Alice", ssn: ssn })
db.patients.find({
  ssn: clientEncryption.encrypt(keyId, "123-45-6789", "deterministic")
})

# automatic CSFLE uses a schema to encrypt per a JSON schema
# { encryptMetadata: { keyId: [keyId], algorithm: "AEAD_AES_256_CBC..." } }
12

バックアップとリストア

mongodump と mongorestore

mongodump は論理バックアップ(BSON ファイル)を作ります — ポータブルですが大きなデータセットには遅く、--oplog なしではコレクション間で時点整合になりません。--drop はリストア前に既存コレクションを削除します。--archive + --gzip で 1 つの圧縮ファイルになります。大規模な本番バックアップには mongodump ではなくファイルシステムスナップショットや Percona Backup が推奨です。

mongodb
# dump an entire database
mongodump --db=mydb --out=/backup/$(date +%F)

# dump a single collection
mongodump --db=mydb --collection=users --out=/backup

# dump with a query filter
mongodump --db=mydb --collection=logs \
  --query='{"date":{"$gte":{"$date":"2025-01-01T00:00:00Z"}}}'

# compress the output archive
mongodump --archive=/backup/full.gz --gzip

# restore from a dump
mongorestore --db=mydb --drop /backup/2025-01-01/mydb
mongorestore --archive=/backup/full.gz --gzip

mongoexport と mongoimport

mongoexport/mongoimport は JSON/CSV を扱います — 他システムとのデータ交換用で、バックアップ用ではありません(ObjectId や Date の精度など BSON の型情報が失われます)。バックアップには mongodump を使いましょう。CSV 出力は表計算や BI ツールに便利です。CSV の列順を安定させるには必ず --fields を指定します。JSON 出力はデフォルトで 1 行 1 ドキュメントです(単一の配列にするには --jsonArray)。

mongodb
# export to JSON (human-readable)
mongoexport --db=mydb --collection=users \
  --out=users.json

# export to CSV
mongoexport --db=mydb --collection=users \
  --type=csv --fields=name,email,age --out=users.csv

# export with a query filter
mongoexport --db=mydb --collection=users \
  --query='{"status":"active"}' --out=active.json

# import from JSON
mongoimport --db=mydb --collection=users --file=users.json

# import from CSV with header row
mongoimport --db=mydb --collection=users \
  --type=csv --headerline --file=users.csv

ファイルシステムスナップショット

ファイルシステムスナップショットは大きなデータセットに対して最速のバックアップ手法です — データディレクトリ全体を一貫した状態で捉えます。fsyncLock で一時的に書き込みを止めてディスクにフラッシュすれば、スナップショットが一貫します。スナップショットはデータ量に関係なくほぼ瞬時に取れます。リストアはファイルを戻すだけ — mongorestore よりはるかに速い。LVM、ZFS、クラウドブロックストレージ(EBS スナップショット)で最も効果を発揮します。

mongodb
# snapshot the dbPath volume for a consistent backup
# 1. flush writes to disk and lock (brief)
db.fsyncLock()

# 2. take a filesystem snapshot (LVM, ZFS, EBS, etc.)
lvcreate --snapshot --size 1G --name mongosnap /dev/vg/data

# 3. unlock the database
db.fsyncUnlock()

# 4. mount the snapshot and copy or back it up
mount /dev/vg/mongosnap /mnt/snap
rsync -a /mnt/snap/ /backup/

# restore: stop mongod, replace dbPath, start mongod
# (fastest restore method for large datasets)

時点復旧(oplog)

時点復旧(PITR)は特定の時刻のデータベース状態を再構築します — 誤削除や失敗したマイグレーションの後に不可欠です。--oplog を付けて定期的にベースバックアップを取り、目的の時刻まで oplog をリプレイします(--oplogLimit で問題の操作の直前で止められます)。PITR にはレプリカセットが必要です(oplog はレプリカセットのメンバーにしか存在しません)。

mongodb
# 1. take a base backup (snapshot or mongodump --oplog)
mongodump --archive=/backup/base.gz --oplog --gzip

# 2. note the time of the accident
# 3. replay the oplog up to just before the error

# dump the oplog from a secondary
mongodump --db=local --collection=oplog.rs \
  --query='{"ts":{"$gt":{"$timestamp":{"t":1700000000,"i":1}}}}' \
  --out=/oplog_dump

# restore the base backup, then replay oplog
mongorestore --archive=/backup/base.gz --oplogReplay \
  --oplogLimit=1700000123:1   # stop before this timestamp

# for a running replica set, use mongorestore --oplogReplay
# with a BSON oplog file

Atlas バックアップとクラウドの選択肢

MongoDB Atlas は時点復旧付きのマネージド継続バックアップを提供します — クラウド環境では最も簡単です。Percona Backup for MongoDB(PBM)はセルフホストクラスタ向けの代表的なオープンソースバックアップツールで、物理バックアップとレプリカセット・シャーディングクラスタをまたぐ PITR に対応しています。リストア手順は必ずテストしましょう — リストアできないバックアップはバックアップではありません。

mongodb
# MongoDB Atlas: continuous backups with PITR
# configured via UI or Atlas CLI:
atlas backups policies create [clusterId] ...

# on-demand snapshot
atlas backups snapshots create [clusterId] \
  --description "pre-migration" \
  --retentionDays 7

# restore an Atlas snapshot
atlas backups restores start [clusterId] \
  --snapshotId [snapId] \
  --deliveryType automated \
  --targetClusterName [target]

# Percona Backup for MongoDB (PBM) — open source
pbm backup --type=physical
pbm restore [snapshotName]
pbm pitr restore --time "2025-01-15T14:30:00"
13

パフォーマンスと最適化

スロークエリのプロファイリング

データベースプロファイラは slowms(デフォルト 100ms)より遅い操作を system.profile(capped コレクション)に記録します。Level 2 はすべてを記録します — デバッグには便利ですが性能に影響します。millis(所要時間)、nreturned(返した件数)、docsExamined を見て非効率なクエリを探しましょう。終わったらプロファイリングを無効にします。

mongodb
# enable the database profiler
# levels: 0=off, 1=slow ops only, 2=all ops
db.setProfilingLevel(1, { slowms: 100 })

# view profiled operations
db.system.profile.find().sort({ ts: -1 }).limit(5)

# find the slowest operations
db.system.profile.find({ millis: { $gt: 1000 } })
  .sort({ millis: -1 })

# profile a specific collection
db.system.profile.find({ ns: "mydb.users" })

# get current profiling level
db.getProfilingStatus()

# clear the profile collection
db.system.profile.drop()

explain() の深掘り

explain() はチューニングの第一の道具です。COLLSCAN はコレクション全体のスキャン — インデックスを追加しましょう。docsExamined と nReturned の比率が効率の鍵です: 10 件返すのに 10000 件調べているならインデックスが貧弱です。allPlansExecution はプランナーがそのプランを選んだ理由を示します。クエリの等価・ソート・範囲の各フィールドにインデックスを付けましょう(ESR ルール)。

mongodb
# three verbosity modes
db.users.find({age:30}).explain("queryPlanner")     # plan only
db.users.find({age:30}).explain("executionStats")    # + timing
db.users.find({age:30}).explain("allPlansExecution") # + rejected plans

# key metrics to check:
#   winningPlan.stage: COLLSCAN (bad) vs IXSCAN (good)
#   totalKeysExamined: index entries scanned
#   totalDocsExamined: documents fetched
#   nReturned: documents returned
#   executionTimeMillis: total time
#   works: number of work units

# ideal ratio: docsExamined ≈ nReturned
# if docsExamined >> nReturned -> missing or bad index

ワーキングセットとメモリ

性能はワーキングセット(頻繁にアクセスするデータ)が RAM に収まるかどうかに左右されます。wiredTiger.cache の 'pages read into cache' が高いならディスクに当たっています — RAM を増やすか、スキャンを減らすインデックスを追加しましょう。mongotop はどのコレクションが I/O の热点かを、mongostat はクエリ/挿入/更新のレートとフォールトを表示します。compact は削除・更新で生じたディスクの空きを回収します。

mongodb
# check the working set size
db.serverStatus().wiredTiger.cache
# look at: "maximum bytes configured", "current bytes"
#          "pages requested from disk" vs "pages read into cache"

# check storage stats
db.stats()
db.users.stats()
db.users.totalSize()   # data + index size in bytes

# mongotop: time spent reading/writing per collection
mongotop 30   # every 30 seconds

# mongostat: live server stats
mongostat --rowcount 10  # 10 iterations

# compact a collection (reclaims disk, blocks writes pre-4.4)
db.runCommand({ compact: "users" })

コネクションプーリング

MongoDB の接続はそれぞれサーバーメモリを消費します — 数千の接続は性能を劣化させます。接続プーリング(ドライバが再利用可能なプールを管理)を使い、maxPoolSize を負荷に合わせて調整しましょう(50〜100 が典型的)。アプリ全体で 1 つの MongoClient を共有し、リクエストごとに作ってはいけません。ロードバランサーの背後では maxIdleTimeMS で古い接続を再利用から外しましょう。

mongodb
# each connection consumes memory (~1MB) on the server
# limit connections in the driver's connection string
mongodb://host:27017/mydb?maxPoolSize=50

# Node.js driver example
const { MongoClient } = require("mongodb")
const client = new MongoClient(uri, {
  maxPoolSize: 50,        // max connections
  minPoolSize: 5,         // keep-alive connections
  maxIdleTimeMS: 30000,   // close idle conns after 30s
  serverSelectionTimeoutMS: 5000
})

# view current connections on the server
db.serverStatus().connections
# { current: 120, available: 880, totalCreated: 200 }

バルク書き込みとバッチサイズ

バルク書き込みは複数の操作を 1 回の往復にまとめます — 個別の操作よりはるかに速いです。unordered:true はスループットを最大化します(エラーを越えて続行し、シャーディングクラスタでは並列化)。大きなインポートでは、メモリと往復回数のバランスのため 1000〜5000 件ずつバッチ化しましょう。ordered:false を付けた insertMany が最速のロード方法です。

mongodb
# ordered bulk write (stops on first error)
db.users.bulkWrite([
  { insertOne: { document: { name: "A" } } },
  { updateOne: { filter: {n:"B"}, update: {$set:{age:1}} } },
  { deleteOne: { filter: { n: "C" } } }
], { ordered: true })

# unordered bulk write (continues on errors, faster)
db.users.bulkWrite(ops, { ordered: false })

# insertMany is a bulk insert — batch large loads
const docs = Array.from({length: 100000}, (_,i) => ({ i }))
const batch = 1000
for (let i = 0; i < docs.length; i += batch) {
  db.big.insertMany(docs.slice(i, i + batch), { ordered: false })
}
14

Change Streams

変更の監視

Change Stream を使うと、oplog を追いかけることでアプリがデータ変更にリアルタイムに反応できます。各イベントには操作タイプ、完全なドキュメント(fullDocument オプション付きの insert/update の場合)、resume トークンが含まれます。resume トークンを保存しておけば、再起動後もイベントを取りこぼしたり重複させたりせずに再開できます。レプリカセットかシャーディングクラスタが必要です。

mongodb
# open a change stream on a collection
const stream = db.users.watch()

# process change events (Node.js driver)
stream.on("change", (event) => {
  console.log(event.operationType)  // insert|update|delete|replace
  console.log(event.fullDocument)   // the new document
  console.log(event.documentKey)    // the _id
  console.log(event.updateDescription)  // updated fields
})

# resume token enables restart from last position
const token = stream.resumeToken
// store token, then resume later:
const stream2 = db.users.watch([], { resumeAfter: token })

# close the stream
stream.close()

変更イベントのフィルタリング

Change Stream はアグリゲーションパイプラインでフィルタリングできます — 一致するイベントだけがアプリに届き、ノイズが減ります。デフォルトでは update イベントに変更されたフィールドだけが含まれ、完全なドキュメントは含まれません。fullDocument:'updateLookup' で現在のドキュメントを取得します(イベントごとに追加クエリ)。fullDocumentBeforeChange(6.0+)は変更前のドキュメントを含み、監査ログに便利です。

mongodb
# filter with an aggregation pipeline
const stream = db.users.watch([
  { $match: { operationType: "update" } },
  { $match: { "updateDescription.updatedFields.status": "active" } },
  { $project: { fullDocument: 1, documentKey: 1 } }
])

# watch specific operations
{ $match: { operationType: { $in: ["insert", "update"] } } }

# full document lookup on update (fetches current doc)
db.users.watch([], {
  fullDocument: "updateLookup"   // include latest doc on updates
})

# fullDocumentBeforeChange (MongoDB 6.0+)
db.users.watch([], {
  fullDocumentBeforeChange: "whenAvailable"
})

データベース/クラスタ単位の Change Stream

Change Stream は単一コレクション、データベース全体、クラスタ全体を監視できます。データベースとクラスタのストリームには各イベントに名前空間(ns)が含まれるので、どこで変更が起きたか分かります。startAtOperationTime を使うと oplog の特定時点から変更をリプレイできます — ダウンタイム中に取りこぼしたイベントのバックフィルや復旧に便利です。

mongodb
# watch all collections in a database
const stream = db.watch()

# watch all databases in a cluster
const stream = client.watch()

# events include the ns (namespace) field
stream.on("change", (e) => {
  console.log(e.ns.db + "." + e.ns.coll)
  console.log(e.operationType)
})

# useful for audit logging, cache invalidation,
# cross-system sync, and real-time analytics

# start at a specific timestamp
db.users.watch([], {
  startAtOperationTime: Timestamp(1700000000, 1)
})

Resume トークンと信頼性

Resume トークンは at-least-once 配信を保証します — 各イベントを処理した後に保存しておけば、再起動時にちょうど続きから再開できます。resumeAfter と startAfter は似ていますが、startAfter はコレクション無効化イベント(drop など)の後でも動作します。必ずエラーを処理し、最後のトークンで再接続しましょう。トークンは不透明なのでブラックボックスとして扱います。

mongodb
# each event has a resume token (_id)
stream.on("change", (e) => {
  saveToStore(e._id)        // persist the token
  processEvent(e)
})

# after a restart, resume from the last token
const lastToken = loadFromStore()
const stream = db.users.watch([], {
  resumeAfter: lastToken     // resume after this event
})

# alternative: start after a cluster time
db.users.watch([], { startAfter: lastToken })

# handle errors and reconnect
stream.on("error", (err) => {
  console.error("stream error", err)
  // reconnect with the last saved token
})

# the token is opaque — store it, don't parse it

Change Stream のユースケース

Change Stream はリアルタイム構成の要です: キャッシュ無効化(古いキャッシュエントリの削除)、ライブ通知(WebSocket プッシュ)、監査ログ(コンプライアンスのため全変更を記録)、ETL/同期(Elasticsearch、DWH、別システムへの複製)。手動ポーリングやトリガーを、きれいなリアクティブなイベント駆動モデルに置き換えます。

mongodb
# 1. Cache invalidation: clear cache when data changes
stream.on("change", (e) => {
  redis.del("user:" + e.documentKey._id)
})

# 2. Real-time notifications: push to WebSocket clients
stream.on("change", (e) => {
  io.emit("user-updated", e.fullDocument)
})

# 3. Audit log: record all changes to a separate store
stream.on("change", (e) => {
  auditLog.insertOne({
    op: e.operationType,
    doc: e.fullDocument,
    at: new Date()
  })
})

# 4. ETL: sync to a search index or warehouse
stream.on("change", async (e) => {
  await elasticsearch.index(e.fullDocument)
})
15

管理とツール

サーバーステータスと監視

serverStatus() は監視の主情報源です — 接続数、opcounters、キャッシュヒット率、レプリケーションラグを追いましょう。currentOp は実行中の操作を表示し、killOp は opid で長時間実行のクエリを止めます。監視エージェント(Prometheus、Datadog、Atlas)を設置して継続的にメトリクスを収集しましょう。重要なアラート: 接続数が上限に近づく、キャッシュヒット率の低下、レプリケーションラグの急増。

mongodb
# overall server status
db.serverStatus()

# key metrics to monitor:
db.serverStatus().connections       # active/idle connections
db.serverStatus().opcounters         # queries/inserts/updates/sec
db.serverStatus().wiredTiger.cache   # cache hit ratio (aim >95%)
db.serverStatus().metrics.document   # docs inserted/returned/deleted
db.serverStatus().repl               # replication state

# current operations (find long-running ops)
db.currentOp({ secs_running: { $gte: 5 } })

# kill a long-running operation
db.killOp(opid)

# host info (CPU, OS, memory)
db.hostInfo()

データベース・コレクションの統計

stats() はストレージの詳細を表示します: dataSize(論理)、storageSize(物理、WiredTiger 圧縮後 — しばしば 50〜80% 小さい)、indexSize。estimatedDocumentCount は瞬時に返ります(コレクションのメタデータから)が概算です。countDocuments({}) は正確ですがスキャンします。ダッシュボードには概算件数、課金には正確な件数を使いましょう。ストレージの増加傾向を監視してキャパシティ計画に役立てます。

mongodb
# database-level stats
db.stats()
db.stats(1024*1024)   # in MB

# collection-level stats
db.users.stats()
db.users.dataSize()       # uncompressed data size
db.users.storageSize()    # on-disk size (with compression)
db.users.totalIndexSize() # total index size
db.users.totalSize()      # data + indexes

# count documents (accurate, may be slow)
db.users.countDocuments({})

# estimated count (fast, from metadata)
db.users.estimatedDocumentCount()

# list collections with sizes
db.runCommand({ listCollections: 1 })

compact と repair

WiredTiger は解放されたディスク領域を再利用するので、compact が必要になるのは滅多にありません — コレクションの大半を削除した後くらいです。compact はコレクションへの操作をブロックし(4.4 未満)、4.4+ ではオンラインで実行できます。repairDatabase は全データを書き直す破壊的な最終手段です — 必ず先にバックアップを取ること。レプリカセットでの領域回収は、セカンダリを再同期する方が安全です(データを削除して再複製させる)。

mongodb
# compact: reclaim disk space from deleted/updated docs
# (WiredTiger reuses freed space, so rarely needed)
db.runCommand({ compact: "users" })

# fullDatabase compact (compact every collection)
db.getCollectionNames().forEach(c => {
  db.runCommand({ compact: c })
})

# repairDatabase (legacy, rewrites all data — last resort)
# Stops the server! Back up first.
mongod --repair --dbpath /data/db

# check data integrity (validates BSON)
db.users.validate({ full: true })

# reclaim space by re-syncing a secondary instead
# (safer than repair on a running primary)

mongotop と mongostat

mongostat はサーバー負荷のリアルタイム概観(insert、query、キャッシュ使用率、接続数)を提供します — MongoDB 版の top/vmstat です。mongotop はどのコレクションが I/O 時間を消費しているかを表示し、ホットコレクションを見つけるのに非常に役立ちます。どちらも MongoDB に同梱されています。本番の監視では、mongod のログと serverStatus のメトリクスを監視システムへ送り履歴分析に使いましょう。

mongodb
# mongostat: live server stats (like vmstat for MongoDB)
mongostat
mongostat --host=host:27017 --rowcount 10
# columns: insert/query/update/delete/getmore/command
#          dirty (cache %), used (cache %), conn, time

# mongotop: time spent per collection (read/write)
mongotop
mongotop 30          # every 30 seconds
mongotop --host=host:27017

# columns: ns (namespace), total/read/write time (ms)
# helps identify which collections are I/O hot

# log slow queries in the mongod log
# set in mongod.conf:
# operationProfiling:
#   mode: slowOp
#   slowOpThresholdMs: 100

設定と起動

本番の MongoDB は設定ファイル(YAML 形式の mongod.conf)で動かします。重要な設定: cacheSizeGB は WiredTiger の RAM を制限(デフォルトは RAM の 50% — 共有サーバーでは明示的に設定)、bindIp はネットワークアクセスを制限、authorization は認証を有効化、replSetName/clusterRole はレプリケーション/シャーディングを有効化。mongod.conf は必ず見直してバージョン管理しましょう。serverCmdLineOpts で有効な設定を確認できます。

mongodb
# start mongod with a config file
mongod --config /etc/mongod.conf

# typical mongod.conf (YAML)
storage:
  dbPath: /var/lib/mongodb
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4        # limit RAM usage
  journal:
    enabled: true
net:
  port: 27017
  bindIp: 127.0.0.1
security:
  authorization: enabled
replication:
  replSetName: rs0
sharding:
  clusterRole: shardsvr

# view current configuration
db.serverCmdLineOpts()
db.runCommand({ getCmdLineOpts: 1 })
16

ドライバと連携

Node.js ドライバ

Node.js ドライバは async/await ベースで ES6+ を完全にサポートします。接続プーリングを使いましょう(アプリごとに 1 つの MongoClient を使い回す)。カーソルは非同期 iterable なので、for-await-of で全ドキュメントをメモリに載せずに反復処理できます。シャットダウン時にはクライアントを閉じます。トランザクション、Change Stream、すべてのアグリゲーション機能に対応しています。

mongodb
const { MongoClient } = require("mongodb")

const client = new MongoClient(
  "mongodb://localhost:27017",
  { maxPoolSize: 50 }
)

async function main() {
  await client.connect()
  const db = client.db("mydb")
  const users = db.collection("users")

  // insert
  await users.insertOne({ name: "Alice", age: 30 })

  // find with a cursor
  const cursor = users.find({ age: { $gte: 18 } })
  for await (const doc of cursor) {
    console.log(doc.name)
  }

  // update
  await users.updateOne(
    { name: "Alice" },
    { $inc: { age: 1 } }
  )
}

main().finally(() => client.close())

Python ドライバ(PyMongo)

PyMongo は公式の Python ドライバです。同期型で、非同期なら Motor(asyncio)や Beanie(ODM)を使います。PyMongo のドキュメントは普通の Python dict で、特殊なオブジェクトは不要です。アグリゲーションパイプラインは dict のリストです。コンテキストマネージャのトランザクションパターンなら commit/abort が自動で行われます。接続プーリングを使いましょう(デフォルトの MongoClient は接続をプールします)。

mongodb
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
db = client["mydb"]
users = db["users"]

# insert
users.insert_one({"name": "Alice", "age": 30})

# find
for doc in users.find({"age": {"$gte": 18}}).sort("age", -1):
    print(doc["name"])

# update
users.update_one(
    {"name": "Alice"},
    {"$inc": {"age": 1}}
)

# aggregation
pipeline = [
    {"$group": {"_id": "$city", "count": {"$sum": 1}}},
    {"$sort": {"count": -1}}
]
for doc in users.aggregate(pipeline):
    print(doc)

# use a context manager for transactions
with client.start_session() as session:
    with session.start_transaction():
        users.update_one({"n":"A"}, {"$inc":{"bal":-100}}, session=session)
        users.update_one({"n":"B"}, {"$inc":{"bal":100}}, session=session)

ドライバからのインデックス作成

インデックスはリクエストのたびではなく、アプリのセットアップ/マイグレーションスクリプトで作成しましょう。createIndexes(複数形)は 1 回の呼び出しで複数のインデックスを作れます。本番での大きなコレクションへのインデックス構築は時間がかかりますが、MongoDB 4.2+ ではデフォルトでノンブロッキングです。インデックス作成スクリプトもスキーママイグレーションと同じようにバージョン管理しましょう。

mongodb
// Node.js: create indexes
await db.collection("users").createIndex({ email: 1 }, { unique: true })
await db.collection("users").createIndex({ name: "text" })

// Python
users.create_index([("email", 1)], unique=True)
users.create_index([("name", "text")])

// list indexes
const indexes = await db.collection("users").indexes()

// drop an index
await db.collection("users").dropIndex("email_1")

// create indexes in bulk
await db.collection("orders").createIndexes([
  { key: { customerId: 1 } },
  { key: { status: 1, date: -1 }, name: "status_date" }
])

接続文字列のオプション

接続文字列はクライアント設定のすべてをクエリパラメータとして運びます。mongodb+srv は DNS SRV レコードでホストを発見します — Atlas はこの形式で、接続文字列が簡潔になりノード変更時に自動更新されます。retryWrites=true(最新ドライバのデフォルト)はネットワーク障害後の冪等な書き込みを自動リトライします。接続が固まるのを避けるため適切なタイムアウトを設定しましょう。

mongodb
# standard connection string
mongodb://user:pass@host1:27017,host2:27017/mydb?replicaSet=rs0

# common options (as query params):
#   replicaSet=rs0            - replica set name
#   readPreference=secondary  - route reads to secondaries
#   readConcernLevel=majority - read committed data
#   w=majority                - write concern
#   journal=true              - wait for journal flush
#   maxPoolSize=50            - max connections
#   connectTimeoutMS=5000     - connection timeout
#   socketTimeoutMS=30000     - socket timeout
#   authSource=admin          - db for credentials
#   tls=true                  - enable TLS
#   retryWrites=true          - retry on network errors

# SRV connection string (Atlas, uses DNS)
mongodb+srv://user:[email protected]/mydb

ODM と高レベルライブラリ

ODM(Object Document Mapper)はスキーマ、バリデーション、高レベル API を追加します。Mongoose(Node.js)が最も人気で、MongoDB にネイティブに欠けている構造を強制します。Beanie は Python の代表的な非同期 ODM です。ODM は迅速な開発とチームの一貫性に優れますが、オーバーヘッドがあり MongoDB の力を隠してしまうこともあります。性能重視のアプリでは素のドライバを使いましょう。

mongodb
// Mongoose (Node.js ODM with schemas)
const mongoose = require("mongoose")
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  age: { type: Number, min: 0 }
})
const User = mongoose.model("User", userSchema)
await User.create({ name: "Alice", age: 30 })
await User.find({ age: { $gte: 18 } })

# Beanie (Python async ODM)
from beanie import Document
class User(Document):
    name: str
    age: int
await User(name="Alice", age=30).insert()
await User.find(User.age >= 18).to_list()

# Mongose vs raw driver:
# ODMs add schemas, validation, and middleware
# but add overhead and a learning curve
# use the raw driver for max performance/control
17

GridFS と大きなファイル

GridFS の基本

GridFS は 16MB の BSON ドキュメント上限を超えるファイルを、チャンク(デフォルト 255KB)に分割して fs.chunks に保存し、メタデータを fs.files に置きます。実質、MongoDB の上に作ったファイルシステムです。16MB を超えるが MongoDB のレプリケーションやシャーディングの恩恵を受けたいファイルに向きます。 truly に巨大なメディアには S3 や CDN を検討しましょう。

mongodb
# GridFS stores files larger than 16MB (the BSON doc limit)
# by splitting them into chunks

# store a file via mongofiles (CLI)
mongofiles --db=mydb put large_video.mp4
mongofiles --db=mydb list
mongofiles --db=myfs get large_video.mp4

# two collections are used:
#   fs.files  - file metadata (one doc per file)
#   fs.chunks - file data in 255KB chunks

# query file metadata
db.fs.files.find().pretty()
db.fs.files.findOne({ filename: "large_video.mp4" })

# query chunks for a file
db.fs.chunks.find({ files_id: fileId }).sort({ n: 1 })

ドライバからの GridFS

ドライバは GridFS をストリーミング API(GridFSBucket)として公開します — ファイル全体をメモリに載せないため大きなファイルに理想的です。アップロード/ダウンロードはファイルや HTTP レスポンスへパイプできるストリームです。アップロード時の metadata は通常のドキュメントフィールドと同様にクエリ可能です。GridFS のチャンクはダウンロード時に自動で再構成されます。バケット名(デフォルト 'fs')は設定可能です。

mongodb
// Node.js: upload and download with streams
const { MongoClient, GridFSBucket } = require("mongodb")
const fs = require("fs")

const bucket = new GridFSBucket(db)

// upload a file
fs.createReadStream("video.mp4")
  .pipe(bucket.openUploadStream("video.mp4", {
    metadata: { uploadedBy: "alice" }
  }))

// download a file
bucket.openDownloadStreamByName("video.mp4")
  .pipe(fs.createWriteStream("downloaded.mp4"))

// delete a file
await bucket.delete(fileId)

// find files
const files = await bucket.find({}).toArray()

時系列コレクション

時系列コレクション(5.0+)は時刻順のシーケンシャルデータ(IoT センサー、メトリクス、ログ)に最適化されています。内部では列指向に近い形式で保存され、通常のコレクションより 30〜50% 圧縮され、範囲クエリも速いです。granularity はデータの間隔に合わせましょう。TTL(expireAfterSeconds)で古いデータを自動パージできます。時間バケットの集計には $dateTrunc を使います。

mongodb
# create a time series collection (MongoDB 5.0+)
db.createCollection("temperatures", {
  timeseries: {
    timeField: "timestamp",
    metaField: "sensorId",
    granularity: "seconds"   // seconds|minutes|hours
  },
  expireAfterSeconds: 2592000   // auto-delete after 30 days
})

# insert measurements
db.temperatures.insertMany([
  { timestamp: ISODate(), sensorId: "s1", value: 22.5 },
  { timestamp: ISODate(), sensorId: "s1", value: 22.7 }
])

# query by time range
db.temperatures.find({
  sensorId: "s1",
  timestamp: { $gte: ISODate("2025-01-01") }
})

# aggregate averages per hour
db.temperatures.aggregate([
  { $group: {
    _id: { $dateTrunc: { date: "$timestamp", unit: "hour" } },
    avg: { $avg: "$value" }
  }}
])

Capped コレクション

Capped コレクションは挿入順を維持し、満杯になると最も古いドキュメントを上書きします — ログ、最近のアクティビティフィード、リングバッファに最適です。高スループットの insert と tailable カーソル(tail -f のようなもの)をサポートします。制限: 個別のドキュメントを削除できず、元のサイズを超えてドキュメントを成長させられません。リアルタイムの tailing には Change Stream が現代的な代替です。

mongodb
# capped collections have a fixed size and overwrite old docs
db.createCollection("logs", {
  capped: true,
  size: 5242880,    # 5MB max
  max: 10000        # optional: max document count
})

# inserts only (no arbitrary deletes/updates)
db.logs.insertOne({ msg: "started", t: new Date() })

# high-throughput tail with a tailable cursor
const cursor = db.logs.find().addOption(2)  // tailable
while (true) {
  if (cursor.hasNext()) printjson(cursor.next())
}

# convert a regular collection to capped
db.runCommand({
  convertToCapped: "events",
  size: 1000000
})

BSON サイズとドキュメント上限

16MB の BSON ドキュメント上限はハードリミットです — Object.bsonsize() でドキュメントサイズを確認しましょう。大きな配列(数千要素)はドキュメントを肥大化させ、更新を遅くします(MongoDB は更新時にドキュメント全体を書き直すため)。無制限に増えるデータ(レビュー、コメント、ログ)は参照付きの別コレクションにしましょう。16MB を超えるバイナリ blob は GridFS か、URL 参照付きの外部ストレージを使います。

mongodb
# maximum BSON document size: 16MB
# check a document's size (in bytes)
Object.bsonsize(db.users.findOne())

# large arrays/fields should be referenced, not embedded
# a product with 10000 reviews -> use a separate collection

# check if a document is too large
const doc = { /* ... huge doc ... */ }
const size = Object.bsonsize(doc)
if (size > 16 * 1024 * 1024) {
  throw new Error("Document exceeds 16MB BSON limit")
}

# GridFS bypasses the limit by chunking
# alternatively, store large blobs externally (S3)
# and keep only a URL reference in the document
18

SQL との比較と移行

SQL と MongoDB の対応

この対応表は SQL 開発者が MongoDB を学ぶ最短ルートです。最大の違い: MongoDB には固定スキーマがなく(同じコレクション内でもドキュメントは異なってよい)、'結合' は関連データの埋め込みか $lookup(SQL の結合より遅い — スキーマ設計で最小化しましょう)で置き換えます。SQL の GROUP BY は $group アグリゲーションステージに対応します。

mongodb
# SQL -> MongoDB terminology
# database          -> database
# table             -> collection
# row               -> document
# column            -> field
# index             -> index
# join              -> $lookup (or embed)
# primary key       -> _id (ObjectId by default)
# foreign key       -> reference (ObjectId field)
# group by          -> $group
# select            -> find / $project
# where             -> $match

# SQL query -> MongoDB query
# SELECT * FROM users WHERE age >= 18
db.users.find({ age: { $gte: 18 } })

# SELECT name, age FROM users
db.users.find({}, { name: 1, age: 1, _id: 0 })

# SELECT * FROM users ORDER BY age DESC LIMIT 10
db.users.find().sort({ age: -1 }).limit(10)

# SELECT city, COUNT(*) FROM users GROUP BY city
db.users.aggregate([
  { $group: { _id: "$city", count: { $sum: 1 } } }
])

SQL からの移行

移行はテーブルからコレクションへの 1:1 マッピングではありません — MongoDB のドキュメントモデルに合わせてスキーマを再設計する必要があります。小さく排他的で一緒に読むデータは埋め込み(ユーザーのプロフィール+住所)。大きい、共有される、無制限のデータは参照のまま(顧客の注文)。MongoDB の Relational Migrator ツールがこの分析の大部分を自動化します。ただ移植するのではなく、スキーマを計画しましょう。

mongodb
# step 1: export SQL data to JSON/CSV
# (mysqldump, pg_dump, or a script)

# step 2: transform relational data to documents
# SQL:
#   users(id, name, dept_id)
#   departments(id, name)
# MongoDB (embed small, related data):
db.users.insertOne({
  _id: 1,
  name: "Alice",
  department: { id: 10, name: "Engineering" }  # embedded
})

# step 3: for large related data, keep references
db.orders.insertOne({
  _id: 101,
  customerId: 1,    # reference, not embedded
  items: [...]      # embed order items (bounded)
})

# tools: MongoDB Relational Migrator (GUI), mongoimport
# https://www.mongodb.com/.../relational-migrator

トランザクションと SQL ACID

MongoDB は ACID を提供します: 単一ドキュメントの操作は常にアトミック(トランザクション不要)で、マルチドキュメントトランザクション(4.0+)はコレクションをまたぐ完全な ACID を提供します。最大の違い: SQL はすべてのステートメントでデフォルト ACID、MongoDB は関連データを 1 ドキュメントに収める(デフォルトでアトミック)スキーマ設計を推奨し、トランザクションは本当に必要なときだけ使います。トランザクションのオーバーヘッドを避けるため埋め込みを優先しましょう。

mongodb
# SQL: ACID by default on every statement
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice';
UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob';
COMMIT;

# MongoDB: single-document ops are atomic (ACID)
db.accounts.updateOne({name:"Alice"}, {$inc:{balance:-100}})
# (one document = one atomic operation)

# MongoDB: multi-document ACID (transactions, replica set)
const s = db.getMongo().startSession()
s.startTransaction()
db.accounts.updateOne({name:"Alice"},{$inc:{balance:-100}},{session:s})
db.accounts.updateOne({name:"Bob"},{$inc:{balance:100}},{session:s})
s.commitTransaction()

# prefer embedding to avoid transactions entirely
# (embedded data updates atomically in one document)

正規化 vs 非正規化

SQL は重複を避けるために正規化し、MongoDB は読み取り速度のために非正規化します。トレードオフ: 非正規化データは読むのが速いが更新が難しい(複数ドキュメントに手を入れる)。めったに変わらないデータ(国名、商品カタログ)は非正規化し、頻繁に変わるデータ(価格、在庫)は参照しましょう。適切なバランスは読み書きの比率次第です — 監視して調整します。

mongodb
# SQL: normalize to avoid duplication (3NF)
#   users(id, name, city_id)
#   cities(id, name, country_id)
#   countries(id, name)
# -> 4 joins to get a user's country

# MongoDB: denormalize for read performance
db.users.insertOne({
  name: "Alice",
  city: "NYC",
  country: "USA"        # denormalized — duplicate but fast reads
})

# trade-off: updates must touch multiple documents
# when a city's name changes:
db.users.updateMany(
  { "city": "New York" },
  { $set: { "city": "NYC" } }
)

# rule: duplicate data that changes rarely,
# reference data that changes often

MongoDB vs SQL の使い分け

万能の「最良」データベースはありません。MongoDB は柔軟なスキーマ、階層データ、水平スケーリングに強く、SQL はリレーショナル整合性、複雑な結合、重いトランザクション処理に強いです。多くの現代アプリはポリグロットです — カタログ/コンテンツ/ユーザー生成データは MongoDB、金融トランザクションは PostgreSQL。流行ではなくワークロードに合わせて選びましょう。

mongodb
# CHOOSE MongoDB when:
# - schema is flexible or evolving rapidly
# - data is naturally hierarchical (embed)
# - you need horizontal scaling (sharding)
# - reads >> writes and you can denormalize
# - document-oriented domain (CMS, product catalogs, IoT)

# CHOOSE SQL (PostgreSQL/MySQL) when:
# - schema is fixed and relational (banking, ERP)
# - you need complex multi-table joins frequently
# - transactions span many tables constantly
# - strong consistency is non-negotiable
# - your team knows SQL well

# HYBRID: use both — MongoDB for product catalog/comments,
# SQL for orders/payments. Many large apps are polyglot.

# AVOID MongoDB for:
# - heavy multi-entity transactional workloads
# - apps requiring complex cross-table joins as core feature
19

高度なアグリゲーション

$merge と $out(マテリアライズドビュー)

$out はパイプラインの出力でターゲットコレクションを置き換えます(破壊的)。$merge の方が柔軟で、既存ドキュメントへの insert、replace、結合ができ、差分更新のマテリアライズドビューを実現します。定期リフレッシュには $merge が推奨です — 新規/変更データだけが更新されます。マテリアライズドビューは重い集計を事前計算し、ダッシュボードのクエリを速くします。

mongodb
# $out: write aggregation results to a NEW collection
db.orders.aggregate([
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
  { $out: "customer_totals" }
])

# $merge: merge results into an EXISTING collection (flexible)
db.orders.aggregate([
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
  { $merge: {
    into: "customer_totals",
    on: "_id",
    whenMatched: "replace",    // replace|keepExisting|merge|fail
    whenNotMatched: "insert"   // insert|discard|fail
  }}
])

# build a materialized view refreshed on a schedule
# (cron job or change-stream triggered)
db.daily_stats.aggregate([
  { $match: { date: today } },
  { $group: { _id: "$category", count: { $sum: 1 } } },
  { $merge: { into: "daily_stats", whenMatched: "replace" } }
])

ウィンドウ関数($setWindowFields)

$setWindowFields(5.0+)は SQL のウィンドウ関数を MongoDB に持ち込みます: 累計、順位、移動平均、lag/lead。partitionBy は PARTITION BY、sortBy は ORDER BY、window がフレームの定義です。範囲ウィンドウは値で指定し(過去 7 日間など)、documents ウィンドウは行数で指定します。時系列分析とレポーティングに不可欠です。

mongodb
# $setWindowFields: window functions (MongoDB 5.0+)
# like SQL OVER() — compute values across a window of docs
db.sales.aggregate([{
  $setWindowFields: {
    partitionBy: "$region",       # like PARTITION BY
    sortBy: { date: 1 },          # like ORDER BY
    output: {
      runningTotal: { $sum: "$amount", window: { documents: ["unbounded", "current"] } },
      rank: { $rank: {} },
      denseRank: { $denseRank: {} },
      movingAvg: { $avg: "$amount", window: { range: [-7, "current"], unit: "day" } },
      lagValue: { $shift: { by: -1, output: "$amount" } }
    }
  }
}])

# window: documents (count-based) or range (value-based)
# ["unbounded", "current"] = from start to current row
# [-3, "current"] = last 3 docs including current

$map、$filter、$reduce

$map、$filter、$reduce はドキュメント内の配列を変換する関数型の配列演算子です。$map は各要素を変換し、$filter は一致する要素を残し、$reduce は配列を 1 つの値に集約します。'as' の変数(デフォルト $$this)が現在の要素を指します。多くの配列操作で $unwind を避けられます — より速くきれいです。

mongodb
# $map: transform each array element
{ $project: {
  squares: { $map: {
    input: "$nums",
    as: "n",
    in: { $multiply: ["$$n", "$$n"] }
  }}
}}

# $filter: keep elements matching a condition
{ $project: {
  adults: { $filter: {
    input: "$users",
    as: "u",
    cond: { $gte: ["$$u.age", 18] }
  }}
}}

# $reduce: fold an array into a single value
{ $project: {
  total: { $reduce: {
    input: "$items",
    initialValue: 0,
    in: { $add: ["$$value", "$$this.price"] }
  }}
}}

# variables: $$value (accumulator), $$this (current element), $$n (named)

$facet とマルチパイプライン

$facet は同じ入力に対して複数のサブパイプラインを 1 クエリで実行します — データの複数の見方(内訳、統計、top N)が必要なダッシュボードに最適です。各サブパイプラインは独立しています。結果はサブパイプラインごとのフィールドを持つ 1 つのドキュメントです。複数回の往復を置き換え、一貫したスナップショットを保証します。

mongodb
# run several aggregations on the same data in one pass
db.products.aggregate([{
  $facet: {
    "byCategory": [
      { $group: { _id: "$category", count: { $sum: 1 } } },
      { $sort: { count: -1 } }
    ],
    "priceStats": [
      { $group: { _id: null, avg: { $avg: "$price" }, max: { $max: "$price" } } }
    ],
    "topRated": [
      { $sort: { rating: -1 } },
      { $limit: 5 },
      { $project: { name: 1, rating: 1, _id: 0 } }
    ],
    "totalCount": [{ $count: "n" }]
  }
}])
# result: a single doc with all four arrays/objects

$bucket と $bucketAuto

$bucket はドキュメントを明示的な値の範囲に分類します(SQL の CASE WHEN に相当)— 価格帯、年齢層、ヒストグラムに最適です。$bucketAuto は MongoDB に境界を計算させて目標のバケット数を作らせます(分布が分からないときのデータ探索に便利)。境界は左閉右開(左側を含み右側を含まない)です。

mongodb
# $bucket: group documents into explicit ranges
db.products.aggregate([{
  $bucket: {
    groupBy: "$price",
    boundaries: [0, 50, 100, 500, 1000],
    default: "other",
    output: {
      count: { $sum: 1 },
      names: { $push: "$name" },
      avgPrice: { $avg: "$price" }
    }
  }
}])
# buckets: [0,50), [50,100), [100,500), [500,1000), other

# $bucketAuto: let MongoDB choose the boundaries
db.products.aggregate([{
  $bucketAuto: {
    groupBy: "$price",
    buckets: 5,           # target 5 buckets
    output: { count: { $sum: 1 }, avg: { $avg: "$price" } }
  }
}])
# good for histograms and data exploration
20

監視とトラブルシューティング

監視すべき重要メトリクス

MongoDB の 4 つの黄金シグナル: 接続数(上限接近はリークかプーリング不足の兆候)、キャッシュヒット率(ディスクからの読み取りは RAM 不足の圧力)、レプリケーションラグ(遅れたセカンダリはフェイルオーバー時にデータ消失のリスク)、キューの深さ(ロック競合)。4 つすべてにアラートを設定しましょう。キャッシュヒット率の低下は最優先で見るべき性能警告です。

mongodb
# connections (watch for connection leaks)
db.serverStatus().connections
# { current, available, totalCreated }

# operation rates (queries/inserts/updates/deletes per sec)
db.serverStatus().opcounters

# WiredTiger cache (disk reads = cache misses)
db.serverStatus().wiredTiger.cache
# "bytes currently in the cache" vs "maximum bytes configured"
# "pages read into cache" should be low (cache hits)

# replication lag (critical for HA)
rs.printSecondaryReplicationInfo()

# queue depth (operations waiting for locks)
db.serverStatus().globalLock.currentQueue

# open cursors (watch for leaks)
db.serverStatus().metrics.cursor

ロック競合の解決

MongoDB(WiredTiger)はドキュメントレベルのロックなので競合は稀ですが、インデックスのないクエリ、巨大なソート、長いトランザクションは依然としてブロックします。currentOp で犯人を特定し、killOp で停止します。根本原因はたいていインデックスの欠落です(explain を実行)。大きなコレクションのスキーママイグレーションは長時間ロックし得ます — 小さなバッチに分けるか、トラフィックの少ない時間帯に実行しましょう。

mongodb
# check current queue (operations waiting)
db.serverStatus().globalLock.currentQueue
# { readers, writers, total }

# find long-running operations
db.currentOp({
  secs_running: { $gte: 5 },
  op: { $ne: "none" }
})

# kill a long-running op blocking others
db.killOp(opid)

# common causes of lock contention:
# - unindexed queries (COLLSCAN holds locks)
# - large in-memory sorts
# - long transactions
# - schema migrations on large collections

# check for slow ops in the log
db.adminCommand({ getLog: "global" }).log
  .filter(l => l.includes(" Slow query"))

メモリとディスクの分析

WiredTiger のキャッシュがメモリの最前線です — ダーティページで満杯だと書き込みが遅くなります(ディスクへのフラッシュ)。'pages read into cache' が高いなら RAM を増やすかスキャンを減らすインデックスを追加しましょう。使っていないインデックスは削除しましょう — ディスクとメモリを消費し書き込みも遅くします。ストレージの増加を監視してキャパシティを予測します。シャーディングクラスタでは、移行できない jumbo chunk はシャードキーが貧弱なサインです。

mongodb
# check storage engine memory usage
db.serverStatus().wiredTiger.cache
# "maximum bytes configured" = cache limit (default 50% RAM)
# "tracked dirty bytes" = dirty pages awaiting flush
# target: dirty < 20%, cache usage < 95%

# disk space per collection
db.users.stats().storageSize
db.users.totalIndexSize()

# find the largest collections
db.getCollectionNames().map(c => ({
  name: c, size: db.getCollection(c).storageSize()
})).sort((a,b) => b.size - a.size).slice(0, 5)

# check for jumbo chunks (sharded clusters)
sh.status(true)

# review index sizes (drop unused indexes)
db.users.getIndexes().map(i => ({
  name: i.name, size: db.users.stats().indexSizes[i.name]
}))

ログ分析

mongod のログにはスローな操作、選挙、エラーなどが記録されます。SLO 以上のクエリを捕捉するため slowOpThresholdMs を設定しましょう。getLog はメモリ内のリングバッファを取得し、ディスク上のログは再起動後も残ります。logRotate は現在のログをアーカイブします(日次ローテーションには logrotate と併用)。深くデバッグするときは一時的にコンポーネントの冗長度を上げ(選挙問題なら replication: 2 など)、終わったら戻しましょう。

mongodb
# view recent log entries
db.adminCommand({ getLog: "global" })

# log slow queries (set threshold)
db.adminCommand({
  setParameter: 1,
  logComponentVerbosity: { query: { verbosity: 1 } }
})

# mongod.conf: log slow operations
# operationProfiling:
#   mode: slowOp
#   slowOpThresholdMs: 100
#   slowOpSampleRate: 1.0

# grep the mongod log for slow queries
grep "Slow query" /var/log/mongodb/mongod.log
grep "COMMAND" /var/log/mongodb/mongod.log | tail -50

# rotate logs
db.adminCommand({ logRotate: 1 })

# set log verbosity for a component
db.adminCommand({
  setParameter: 1,
  logComponentVerbosity: { replication: 2 }
})

よくあるエラーと対処法

これらは MongoDB で最もよくあるエラーです。Duplicate key エラーは _id やユニークインデックスの違反で起こります — アプリコードで処理しましょう。アグリゲーションのメモリ上限は allowDiskUse で解決します(遅いが動く)。トランザクションの WriteConflict は競合下では正常です — リトライしましょう。Cursor timeout はバッチ処理が遅すぎるサインです — バッチを小さくするか noCursorTimeout を使います(ただし必ずカーソルを閉じること)。

mongodb
# ERROR: "E11000 duplicate key"
# cause: _id or unique index conflict
# fix: check the duplicate value, use upsert, or catch the error

# ERROR: "QueryExceededMemoryLimitNoDiskUseAllowed"
# cause: aggregation stage exceeded 100MB RAM
# fix: add { allowDiskUse: true } or add $match early
db.big.aggregate([...], { allowDiskUse: true })

# ERROR: "BSONObjTooLarge"
# cause: document > 16MB
# fix: use GridFS or split the document

# ERROR: "WriteConflict" (transaction)
# cause: two transactions modified the same doc
# fix: retry the transaction (TransientTransactionError)

# ERROR: "ReplicaSetNoPrimary"
# cause: no primary (election in progress)
# fix: wait for election; check rs.status()

# ERROR: "cursor not found"
# cause: cursor timed out (10 min default)
# fix: use noCursorTimeout or process faster

Was this helpful?