2020-05-01

MongoDB 資料格式驗證 (json schema validation)

MongoDB 資料格式驗證 (json schema validation)

MongoDB 雖然在儲存的資料上很有彈性,但在很多時候太彈性的資料反而不好處理。所以在 collections 上也提供了格式驗證的功能,當設定了 $jsonSchema 表示新增的資料或修改後的資料都必須符合設定的格式。

官方的格式驗證說明 的例子來說明,可以在建立 collection 時,設定格式驗證規則:

db.createCollection("students", { validator: { $jsonSchema: { bsonType: "object", // 文件的類型 required: [ "name", "year", "major", "address" ], // 必要欄位 properties: { name: { bsonType: "string", // 欄位類型:字串 description: "說明的文字" }, year: { bsonType: "int", minimum: 2017, // 最小值 maximum: 3017 // 最大值 }, major: { enum: [ "Math", "English", "Computer Science", "History", null ], description: "必須是上列的其中一個" }, gpa: { bsonType: "double", description: "must be a double if the field exists" }, address: { bsonType: "object", required: [ "city" ], // 必要的子欄位 properties: { street: { bsonType: "string", description: "must be a string if the field exists" }, city: { bsonType: "string", "description": "must be a string and is required" } } } } } } })

BSON Types 的官方參考

也可以使用 collMod 指令,變更 collection 的格式驗證規則:

db.runCommand({ collMod: "contacts", validator: { $jsonSchema: { bsonType: "object", required: ["phone"], properties: { phone: { bsonType: "string", description: "must be a string and is required" }, email: { bsonType: "string", pattern: "@mongodb\.com$", description: "must be a string and match the regular expression pattern" }, status: { enum: ["Unknown", "Incomplete"], description: "can only be one of the enum values" } } } }, validationLevel: "moderate", validationAction: "warn" })

使用 db.getCollectionInfos() 可以顯示各個 collections 的詳細訊息。

> db.runCommand({ collMod: "compoundTest", validator: { $jsonSchema: { bsonType: "object", required: ['a', 'b'], properties: { a: { bsonType: "int" }, b: { bsonType: "int" } } } }, validationLevel: "moderate", // 等級 validationAction: "warn" // 沒通過時 }) > db.getCollectionInfos({name: 'compoundTest'})

沒有留言:

FB 留言