32

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?

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
Arpit Solanki
  • 433
  • 1
  • 5
  • 10

2 Answers2

56

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.

SLCH000
  • 1,821
  • 2
  • 14
  • 15
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
27

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

Eve Freeman
  • 32,467
  • 4
  • 86
  • 101