Skip to content
All writing Part 08 of 09 · [object Object]
Engineering · 1 min read

MongoDB 運算子與詞彙:把 SQL 意圖翻成文件查詢

把 SQL 意圖翻成 MongoDB:比較、$in、$regex、$exists 等運算子,一張 SQL→Mongo 對照表,以及關聯式→文件的詞彙對照(table = collection、row = document)。

Mongo 講的是 document,所以翻譯的是 operation 的 intent,不是 SQL 的 syntax。

{ field: {$op: value} }

  • Equal $eq:預設,不用寫 operator。{field: <cond>}
  • 其他:{ age: {$gt: 30} }
  • { age: { $gt: 20, $lt: 40 } } // 20 < age < 40

常用 operator

  • 比較
    • $gt / $gte / $lt / $lte
    • $eq / $ne
    • $in / $nin:符合清單中任一 / 皆不符合,像 SQL 的 IN
      • { type: { $in: ["a","b","c"] } }
  • 字串
    • $regex:像 SQL 的 LIKE
      • { name: { $regex: "abc", $options: "i" } }i = 不分大小寫)
  • 存在
    • $exists:這個欄位存不存在(有這欄位?)
      • Mongo 裡 Absent ≠ null:username: null 是「有欄位、明確沒值」;Absent 是「document 根本沒寫這個 key」
  • 邏輯$or / $and / $nor 吃一個 array
    • { $or: [ { age: { $lt: 18 } }, { vip: true } ] }

SQL → MongoDB

SQLMongoDB
SELECT col{ $project: {...} }(或 find 的 projection 參數)
GROUP BY{ $group: { _id: "$field", ... } }
ORDER BY{ $sort: {...} }
IN (...){ field: { $in: [a, b, c] } }
IS NULL{ field: null }{ field: { $exists: false } }
LIMIT{ $limit: n }

Term:Relational → MongoDB 的關係

Relational (Postgres)MongoDB說明
TableCollection一群 document (資料集)
RowDocument一個 JSON/BSON 物件 (單一資料集)
ColumnField沒有固定 schema,每個 document 欄位可不同
Schema(不強制)schema 彈性、欄位因 document 而異
Primary key_id自動加入、唯一

參考來源

Related: 回到跨引擎資料庫查詢總覽;看 LIKE / ILIKE 子字串搜尋 如何對應到 $regex,以及它如何連回可攜式 SQL 核心

Tags #mongodb #databases
// connect

Be brave | Be wise | Be grateful

21 BreakinCode

// elsewhere
LinkedInMedium (lang: en)Youtube
wh:~$William Hung· © 2026 Taipei · GMT+8 · Available for collaboration