Search code examples
mongodb-.net-driver

Is there Document Validator available for MongoDB using C# driver?


MongoDB documentation talks about how a document validator could be defined on a collection which could be triggered during insert or update.

For example, a collection with email field could be validated using a regex and the insert may succeed or fail depending upon how the collection has been configured at the time of creation.

I have not been able to find similar capability for C# driver for MongoDB.

Is this not supported yet?


Solution

  • This ship may have sailed, but if others stumble across this question. This has been implemented.

    The mainline C# driver as well as the legacy C# driver support document validation. As you see in the documentation, you set a validator when you create a collection (or by using collMod to add a validator to an existing collection, but I won't discuss this further). The driver includes properties inside the CreateCollectionOptions class for the Validator document, the ValidationAction, and ValidationLevel. CreateCollectionOptions is the second argument you pass to the CreateCollection function. Here is the source code and a test that creates a collection with a simple validator and another.