$jsonSchema

适用对象: MongoDB vCore

$jsonSchema 运算符用于根据 JSON 架构规范验证文档。 它确保文档符合预定义的结构、数据类型和验证规则。

Syntax

运算符的 $isArray 语法如下所示:

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 指示数组项是否必须唯一的布尔值。

支持的关键字

Azure Cosmos DB for MongoDB (vCore) 支持以下 JSON 架构关键字:

关键字 类型 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 阵 列 强制实施唯一数组元素 数据完整性

不支持的关键字

Azure Cosmos DB for MongoDB(vCore)中尚不支持这些 JSON 架构关键字:

关键字 类型 非支持的原因 解决方法
additionalProperties 对象 未在 vCore 中实现 使用显式 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:包含数组项的销售验证

此查询检索所有存储文档,其中销售字段是包含非负 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:与查询运算符结合使用

此查询检索所有存储文档,其中员工字段是一个有效对象,其中包含至少一个全职员工(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
  }
]