MongoDB的文檔驗(yàn)證功能可以在集合創(chuàng)建時(shí)指定驗(yàn)證規(guī)則。通過指定驗(yàn)證規(guī)則,可以確保插入的文檔滿足特定的條件。以下是使用文檔驗(yàn)證功能的步驟:
db.createCollection("myCollection", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "gender", "age"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
gender: {
bsonType: "string",
description: "must be a string and is required"
},
age: {
bsonType: "int",
minimum: 0,
description: "must be a positive integer and is required"
}
}
}
}
})
上面的代碼創(chuàng)建了一個(gè)名為myCollection
的集合,并定義了一個(gè)驗(yàn)證規(guī)則,要求插入的文檔必須包含name
、gender
和age
字段,并且name
和gender
必須是字符串類型,age
必須是正整數(shù)。
age
字段的文檔:db.myCollection.insertOne({
name: "Alice",
gender: "female"
})
將會(huì)返回以下錯(cuò)誤:
WriteError({
"index" : 0,
"code" : 121,
"codeName" : "DocumentValidationFailure",
"errmsg" : "Document failed validation",
"op" : {
"name" : "Alice",
"gender" : "female"
}
})
通過使用文檔驗(yàn)證功能,可以確保插入的文檔滿足特定的條件,提高數(shù)據(jù)的完整性和一致性。