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」
- Mongo 裡 Absent ≠ null:
- 邏輯 —
$or/$and/$nor吃一個 array{ $or: [ { age: { $lt: 18 } }, { vip: true } ] }
SQL → MongoDB
| SQL | MongoDB |
|---|---|
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 | 說明 |
|---|---|---|
| Table | Collection | 一群 document (資料集) |
| Row | Document | 一個 JSON/BSON 物件 (單一資料集) |
| Column | Field | 但沒有固定 schema,每個 document 欄位可不同 |
| Schema | (不強制) | schema 彈性、欄位因 document 而異 |
| Primary key | _id | 自動加入、唯一 |
參考來源
- MongoDB Query Operators — https://www.mongodb.com/docs/manual/reference/operator/query/
Related: 回到跨引擎資料庫查詢總覽;看 LIKE / ILIKE 子字串搜尋 如何對應到 $regex,以及它如何連回可攜式 SQL 核心。