Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
   });
like image 456
mortb Avatar asked Nov 02 '25 03:11

mortb


1 Answers

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
       });
like image 182
John Vottero Avatar answered Nov 03 '25 21:11

John Vottero