$jsonSchema

運算 $jsonSchema 子可用來根據 JSON 綱目規格驗證文件。 它確保文件符合預先定義的結構、資料類型和驗證規則。

語法

運算子的 $jsonSchema 語法如下所示:

db.createCollection("collectionName", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["field1", "field2"],
      properties: {
        field1: {
          bsonType: "string",
          description: "Description of field1 requirements"
        },
        field2: {
          bsonType: "int",
          minimum: 0,
          description: "Description of field2 requirements"
        }
      }
    }
  },
  validationLevel: "strict", // Optional: "strict" or "moderate"
  validationAction: "error"   // Optional: "error" or "warn"
})

參數

參數 Description
bsonType 指定欄位必須相符的二進位 JSON (BSON) 類型。 接受$type運算子所使用的字串別名。
properties 定義特定欄位驗證規則的物件。
minimum/maximum 數字欄位的數值限制。
minLength/maxLength 字串長度限制。
minItems/maxItems 陣列長度限制。
pattern 字串驗證的正則運算式模式。
items 陣列元素的結構描述驗證。
uniqueItems 布林值,表示陣列項目是否必須是唯一的。

支援的關鍵字

DocumentDB 支援以下 JSON Schema 關鍵字:

Keyword 類型 Description Usage
additionalItems 陣列 額外陣列項目的結構描述 擴充陣列驗證
bsonType 所有類型 MongoDB 擴充功能 - 接受 BSON 類型別名 "string"、"int"、"double"、"object"、"array"、"bool"、"date"
exclusiveMinimum 數字 獨佔最小邊界 進階數值驗證
exclusiveMaximum 數字 獨佔最大邊界 進階數值驗證
items 陣列 陣列元素的結構描述 陣列元素驗證
minimum 數字 最小值約束 數值驗證
maximum 數字 最大值限制 數值驗證
minItems 陣列 陣列長度下限 陣列大小驗證
maxItems 陣列 陣列長度上限 陣列大小驗證
multipleOf 數字 值必須是指定數字的倍數 數學約束
minLength 字串 最小字串長度 字串驗證
maxLength 字串 字串長度上限 字串驗證
pattern 字串 正規表示式模式比對 字串格式驗證
properties 物件 定義物件欄位的驗證規則 巢狀物件的結構描述定義
required 物件 必要欄位名稱的陣列 強制執行必填欄位
type 所有類型 標準 JSON 結構描述類型 "object"、"array"、"number"、"boolean"、"string"、"null"
uniqueItems 陣列 強制執行唯一的陣列元素 數據完整性

不支援的關鍵字

這些 JSON Schema 關鍵字尚未在 DocumentDB 中被支援:

Keyword 類型 不支持的原因 因應措施
additionalProperties 物件 未實作 使用明確定義properties
allOf 所有類型 不支援邏輯運算子 使用巢狀驗證
anyOf 所有類型 不支援邏輯運算子 使用個別的查詢
dependencies 物件 不支援複雜的相依性驗證 應用程式邏輯中的處理
description N/A 可能不會出現在錯誤訊息中 僅供參考
enum 所有類型 不支援列舉驗證 請改用 $in 運算子
maxProperties 物件 不支援屬性計數驗證 應用程式邏輯中的處理
minProperties 物件 不支援屬性計數驗證 應用程式邏輯中的處理
not 所有類型 不支援否定運算子 使用正面驗證規則
oneOf 所有類型 不支援邏輯運算子 使用應用程式層級驗證
patternProperties 物件 不支援型樣型內容驗證 使用明確的屬性名稱
title N/A 未處理的中繼資料欄位 請改用 description

範例

讓我們探討使用資料集的 stores 實際範例:

{
  "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
  "name": "First Up Consultants | Bed and Bath Center - South Amir",
  "location": {
    "lat": 60.7954,
    "lon": -142.0012
  },
  "staff": {
    "totalStaff": {
      "fullTime": 18,
      "partTime": 17
    }
  },
  "sales": {
    "totalSales": 37701,
    "salesByCategory": [
      {
        "categoryName": "Mattress Toppers",
        "totalSales": 37701
      }
    ]
  }
}

範例 1:基本結構驗證

此查詢會擷取名稱長度介於 5 到 100 個字元之間的所有存放區,且地理座標位於有效範圍內:緯度介於 -90 到 90 之間,經度介於 -180 到 180 之間。

db.stores.find({
  $jsonSchema: {
    bsonType: "object",
    properties: {
      _id: {
        bsonType: "string"
      },
      name: {
        bsonType: "string",
        minLength: 5,
        maxLength: 100
      },
      location: {
        bsonType: "object",
        properties: {
          lat: {
            bsonType: "double",
            minimum: -90,
            maximum: 90
          },
          lon: {
            bsonType: "double",
            minimum: -180,
            maximum: 180
          }
        }
      }
    }
  }
}).limit(1)

範例 2:使用陣列項目進行銷售驗證

此查詢會擷取所有商店文件,其中 sales 欄位是有效物件,其中包含非負 totalSales 值,以及至少一個項目的 salesByCategory 陣列。

db.stores.find({
  $jsonSchema: {
    bsonType: "object",
    properties: {
      sales: {
        bsonType: "object",
        properties: {
          totalSales: {
            bsonType: "int",
            minimum: 0
          },
          salesByCategory: {
            bsonType: "array",
            minItems: 1,
            items: {
              bsonType: "object",
              properties: {
                categoryName: {
                  bsonType: "string",
                  minLength: 1
                },
                totalSales: {
                  bsonType: "int",
                  minimum: 0
                }
              }
            }
          }
        }
      }
    }
  }
}).limit(1)

此查詢應傳回此輸出:

[
  {
    _id: 'new-store-001',
    name: 'Adatum Corporation - Downtown Branch',
    sales: { totalSales: 5000 },
    createdDate: ISODate('2025-06-11T11:11:32.262Z'),
    status: 'new',
    staff: { totalStaff: { fullTime: 0, partTime: 0 } },
    version: 1,
    storeOpeningDate: ISODate('2025-06-11T11:11:32.262Z'),
    storeFeatures: 213
  }
]

範例 3:與查詢運算子結合

此查詢會擷取所有商店文件,其中 staff 欄位是有效物件,其中包含至少一個全職員工 (fullTime ≥ 1) 且 sales.totalSales 大於 10,000 的 totalStaff 子物件。

db.stores.find({
  $and: [
    {
      $jsonSchema: {
        properties: {
          staff: {
            bsonType: "object",
            properties: {
              totalStaff: {
                bsonType: "object",
                properties: {
                  fullTime: {
                    bsonType: "int",
                    minimum: 1
                  }
                }
              }
            }
          }
        }
      }
    },
    // Additional query constraints
    {
      "sales.totalSales": { $gt: 10000 }
    }
  ]
}).limit(1)

此查詢會傳回下列結果:

[
  {
    _id: 'future-electronics-001',
    address: { city: 'New Tech City' },
    name: 'Boulder Innovations - Future Electronics Hub',
    sales: { totalSales: 25000 },
    establishedDate: ISODate('2025-06-11T11:14:23.147Z'),
    categories: [ 'electronics', 'gadgets', 'smart-home' ],
    promotionEvents: [],
    ratings: { average: 0, count: 0, reviews: [] },
    inventory: {
      lastUpdated: ISODate('2025-06-11T11:14:23.147Z'),
      totalItems: 0,
      lowStockAlerts: []
    },
    storeOpeningDate: ISODate('2025-06-11T11:11:32.262Z'),
    storeFeatures: 120
  }
]