Search code examples
.netmongodbmongodb-.net-driver

MongoDb with .NET driver add collection jsonschema validation


Is there any way, when creating a collection in mongodb with the .NET driver, to specify a json schema to validate against?

I have found documentation on how to set a validator using code, but not how to use a json schema to validate.

The reason I'm looking for schema validation in using the .NET driver is that specifying validation using code gets kind of verbose:

db.CreateCollectionAsync(
   "Foos",
   new CreateCollectionOptions<Foo> 
   { 
      Validator = FilterDefinitionBuilder<MongoCustomization>()
        .And(
            new FilterDefinitionBuilder<MongoCustomization>().Exists(c => c.Revision),
            new FilterDefinitionBuilder<MongoCustomization>().Type(c => c.Revision, BsonType.Int32),
            new FilterDefinitionBuilder<MongoCustomization>().Exists(c => c.CreatedBy)), 
      ValidationAction = DocumentValidationAction.Error, 
      ValidationLevel = DocumentValidationLevel.Strict
   });

Solution

  • A few years late but the answer is to use the JsonSchema method of the FilterDefinitionBuilder class. Like this:

        db.CreateCollectionAsync(
           "Foos",
           new CreateCollectionOptions<Foo>
           {
               Validator = new FilterDefinitionBuilder<Foo>().JsonSchema(BsonDocument.Parse("your JSON goes here")),
               ValidationAction = DocumentValidationAction.Error,
               ValidationLevel = DocumentValidationLevel.Strict
           });