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?
2 Answers
MongoDB 3.2 Update
Document validation is now supported natively by MongoDB.
Example from the documentation:
db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
} )
Original answer
To go beyond the uniqueness constraint available natively in indexes, you need to use something like Mongoose and 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.
-
It should be mentioned that according to the link users can bypass this validation. Nevertheless a great tool to have. – SomeDutchGuy Oct 01 '19 at 11:41
-
should this be $and rather than $or ? – Markus May 05 '23 at 12:29
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
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

- 32,467
- 4
- 86
- 101