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

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.

主站蜘蛛池模板: 武强县| 神农架林区| 高安市| 辰溪县| 榆树市| 揭阳市| 鹿泉市| 柯坪县| 宁城县| 江门市| 泌阳县| 兴国县| 高安市| 绥芬河市| 阿拉善右旗| 额济纳旗| 三明市| 宜君县| 正阳县| 黔西| 广安市| 栖霞市| 孝义市| 秦安县| 南康市| 巫溪县| 潞城市| 株洲市| 财经| 嵊州市| 贡嘎县| 抚宁县| 佛坪县| 龙井市| 毕节市| 阿拉尔市| 郁南县| 开江县| 平南县| 噶尔县| 绥阳县|