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

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.

主站蜘蛛池模板: 轮台县| 包头市| 章丘市| 舞阳县| 扎兰屯市| 万盛区| 即墨市| 平凉市| 芦溪县| 易门县| 文化| 余姚市| 龙海市| 乃东县| 视频| 浦东新区| 苍山县| 井研县| 凤山市| 绥滨县| 金乡县| 台东县| 潼关县| 教育| 清水县| 醴陵市| 浦北县| 广安市| 临湘市| 会昌县| 鸡泽县| 台中县| 塔城市| 白水县| 绩溪县| 商都县| 富川| 盐边县| 丰城市| 定襄县| 蓬莱市|