Alternative to schema validation in AWS DocumentDB

1.8k Views Asked by At

I am moving my database in MongoDB to AWS DocumentDB. I am using mongodb-driver (version 3.6.4) in Java to write and read the data, as well as to configure the collections I use. In particular, I have a schema validation (written as a JSON Schema) which seems not to be compatible with AWS DocumentDB.

Here the documentation says that $jsonSchema is not supported, but I have not seen any explicit assertion about document validation in general.

Is it really unsopported? Is there any alternative (besides doing it in the Java code)?

2

There are 2 best solutions below

0
On BEST ANSWER

As pointed out by smthakur19 in a comment above and as I expected, DocumentDB does not have the notion of required properties. However, it does have pre-triggers (e.g. one that runs a stored procedure prior to performing an insert). So it is possible to validate fields within a stored procedure and reject inserts that do not contain required properties in a given document type.

1
On

AWS DocumentDB now supports schema validations and operator $jsonSchema.

To create a collection with schema validations, you can use command (this is an example for aws documentation):

db.createCollection("employees", {
   "validator": {
      "$jsonSchema": {
         "bsonType": "object",
         "title": "employee validation",
         "required": [ "name", "employeeId"],
         "properties": {
            "name": {
                  "bsonType": "object",
                  "properties": {
                     "firstName": {
                        "bsonType": ["string"]
                     },
                     "lastName": {
                        "bsonType": ["string"]
                     }
                  },
                  "additionalProperties" : false 
            },
            "employeeId": {
               "bsonType": "string",
               "description": "Unique Identifier for employee"
            },
             "salary": {
               "bsonType": "double"
            },
            "age": {
               "bsonType": "number"
            }
         },
         "additionalProperties" : true 
      }
   },
   "validationLevel": "strict", "validationAction": "error"
} )

and query documents as per schema document using $jsonSchema:

db.employees.find({ 
       $jsonSchema: { required: ["age"] } })