如何在 MongoDB 中应用约束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12550210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply constraints in MongoDB?
提问by Arpit Solanki
I have started using MongoDB and I am fairly new to it. Is there any way by which I can apply constraints on documents in MongoDB? Like specifying a primary key or taking an attribute as unique? Or specifying that a particular attribute is greater than a minimum value?
我已经开始使用 MongoDB,而且我对它还很陌生。有什么方法可以对 MongoDB 中的文档应用约束?喜欢指定主键或将属性视为唯一?或者指定特定属性大于最小值?
采纳答案by Eve Freeman
Being a "schemaless" database, some of the things you mention must be constrained from the application side, rather than the db side. (such as "minimum value")
作为一个“无模式”数据库,你提到的一些事情必须从应用程序端而不是数据库端进行约束。(例如“最小值”)
However, you can create indexes (keys to query on--remember that a query can only use one index at a time, so it's generally better to design your indexes around your queries, rather than just index each field you might query against): http://www.mongodb.org/display/DOCS/Indexes#Indexes-Basics
但是,您可以创建索引(要查询的键——请记住,一个查询一次只能使用一个索引,因此通常最好围绕您的查询设计索引,而不是仅仅为您可能查询的每个字段建立索引): http://www.mongodb.org/display/DOCS/Indexes#Indexes-Basics
And you can also create unique indexes, which will enforce uniqueness similar to a unique constraint (it does have some caveats, such as with array fields): http://www.mongodb.org/display/DOCS/Indexes#Indexes-unique%3Atrue
您还可以创建唯一索引,这将强制执行类似于唯一约束的唯一性(它确实有一些警告,例如数组字段):http: //www.mongodb.org/display/DOCS/Indexes#Indexes-unique %3真
回答by JohnnyHK
To go beyond the uniqueness constraint available natively in indexes, you need to use something like Mongooseand its ability to support field-based validation. That will give you support for things like minimum value, but only when updates go through your Mongoose schemas/models.
要超越索引中本机可用的唯一性约束,您需要使用Mongoose 之类的东西及其支持基于字段的验证的能力。这将为您提供诸如最小值之类的支持,但仅当更新通过您的 Mongoose 模式/模型时。
MongoDB 3.2 Update
MongoDB 3.2 更新
Document validation is now supported natively by MongoDB.
MongoDB 本身现在支持文档验证。
Example from the documentation:
文档中的示例:
db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
} )