赞
踩
Document Validation
MongoDB provides the capability to validate documents during updates and insertions. Validation rules are specified on a per-collection basis using the validator option, which takes a document that specifies the validation rules or expressions. Specify the expressions using any query operators, with the exception of $geoNear, near,$nearSphere,text, and $where.
Add document validation to an existing collection using the collMod command with the validator option. You can also specify document validation rules when creating a new collection using db.createCollection() with the validator option, as in the following:
下面语句,执行建表,并且通过validator为表增加规则。
db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
} )
$or:至少满足一个表达式(http://docs.mongoing.com/manual-zh/reference/operator/query/or.html)
表达式内容:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
总结:
最终我们了解到,在创建文档时,我们就指定文档中特殊列的规则,对插入和更新操作进行控制。
如下图操作:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。