Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply constraints in MongoDB?

Tags:

mongodb

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?

like image 951
Arpit Solanki Avatar asked Sep 23 '12 06:09

Arpit Solanki


People also ask

How are constraints managed in MongoDB?

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.

How do I set unique fields in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

How do I use distinct aggregation in MongoDB?

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.

Does MongoDB have foreign keys?

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.


1 Answers

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" ] } }       ]    } } ) 
like image 123
JohnnyHK Avatar answered Oct 26 '22 23:10

JohnnyHK