MongoDB中的文檔驗(yàn)證功能怎么使用

小億
90
2024-04-19 14:06:19
欄目: 云計(jì)算

MongoDB的文檔驗(yàn)證功能可以在集合創(chuàng)建時(shí)指定驗(yàn)證規(guī)則。通過指定驗(yàn)證規(guī)則,可以確保插入的文檔滿足特定的條件。以下是使用文檔驗(yàn)證功能的步驟:

  1. 在創(chuàng)建集合時(shí),通過指定驗(yàn)證規(guī)則來啟用文檔驗(yàn)證功能??梢允褂靡韵旅顏韯?chuàng)建帶有驗(yàn)證規(guī)則的集合:
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、genderage字段,并且namegender必須是字符串類型,age必須是正整數(shù)。

  1. 插入文檔時(shí),如果文檔不滿足驗(yàn)證規(guī)則,MongoDB會(huì)返回一個(gè)錯(cuò)誤。例如,如果插入一個(gè)缺少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ù)的完整性和一致性。

0