- Mastering MongoDB 3.x
- Alex Giamas
- 253字
- 2021-08-20 10:10:55
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.
- 32位嵌入式系統與SoC設計導論
- Verilog HDL數字系統設計入門與應用實例
- 輕松學Java Web開發
- TestStand工業自動化測試管理(典藏版)
- 機艙監測與主機遙控
- 永磁同步電動機變頻調速系統及其控制(第2版)
- Embedded Programming with Modern C++ Cookbook
- AI 3.0
- 數據庫系統原理及應用教程(第5版)
- 工業機器人運動仿真編程實踐:基于Android和OpenGL
- 網中之我:何明升網絡社會論稿
- Mastering ServiceNow Scripting
- Extending Ansible
- Apache源代碼全景分析(第1卷):體系結構與核心模塊
- Linux系統下C程序開發詳解