官术网_书友最值得收藏!

collMod

collMod is used to pass flags to a collection modifying the underlying database's behavior.

Since version 3.2, the most interesting set of flags that we can pass to a collection is document validation.

Document validation can specify a set of rules to be applied to new updates and inserts into a collection. This means that current documents will get checked if they get modified.

We can only apply validations to documents that are already valid if we set validationLevel to moderate. By specifying validationAction we can log documents that are invalid by setting it to warn or prevent updates from happening altogether by setting it to error.

For example, with the previous example of BookOrders we can set a validator on the isbn and name fields being present for every insert or update like this:

> db.runCommand( { collMod: "bookOrders",
"validator" : {
"$and" : [
{
"isbn" : {
"$exists" : true
}
},
{
"name" : {
"$exists" : true
}
}
]
}
})

Here, we get back:

{ "ok" : 1 }

Then if we try to insert a new document with only the isbn field being present, we get an error:

> db.bookOrders.insert({isbn: 102})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
>

We get an error because our validation failed. Managing validation from the shell is really useful as we can write scripts to manage them and also make sure that everything is in place.

主站蜘蛛池模板: 太仆寺旗| 汉沽区| 温泉县| 缙云县| 邹平县| 沐川县| 福州市| 河北省| 长寿区| 陵川县| 兴安县| 安新县| 西林县| 林西县| 松江区| 彝良县| 康乐县| 金溪县| 库伦旗| 响水县| 华阴市| 阳城县| 汾阳市| 海伦市| 修文县| 建水县| 淮北市| 晋江市| 石楼县| 股票| 桓台县| 招远市| 肇州县| 治县。| 汝南县| 游戏| 久治县| 南宁市| 临颍县| 绥中县| 香港 |