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's Unique Constraint makes certain that the fields indexed in it, do not store duplicate values for the same field, i.e., making sure the uniqueness of fields. By default, MongoDB enforces this unique constraint on the “_id” field, while inserting new data.
To create a unique index, use the db. collection. createIndex() method with the unique option set to true .
You can use $addToSet with the aggregation framework to count distinct objects. Not a generic solution, if you have a large number of unique zip codes per result, this array would be very large. The question was to get the city with MOST zip codes for each state, not to get the actual zip codes.
MongoDB References Normally, MongoDB doesn't work with the concept of foreign keys. The foreign keys can be used in the Relational Databases for visualizing data from multiple collections simultaneously.
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.
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" ] } } ] } } )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With