How to apply constraints in MongoDB?

前端 未结 2 1714
無奈伤痛
無奈伤痛 2020-12-15 16:57

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

相关标签:
2条回答
  • 2020-12-15 17:52

    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

    0 讨论(0)
  • 2020-12-15 17:54

    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" ] } }
          ]
       }
    } )
    
    0 讨论(0)
提交回复
热议问题