Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure that only certain keys are present in a document using document validator

Tags:

mongodb

While inserting a document I want to check using mongodb document validation feature that all the keys present in the document are from a predefined set of keys. Assume only "a","b","c" are allowed keys and doc1 and doc2 defined below are 2 documents:

{
    "a": "any_value",
    "b":"any_other_value"
},
{
    "a": "any_value",
    "b": "any_other_value",
    "d": "other_value"
}

In this case doc1 is a valid document and doc2 is invalid.

Also, how to do this validation if in above case one more condition is added that all the keys must be present?

Note: I want to know if this can be done by Document Validation feature present in MongoDB 3.2

like image 925
tpnsharma Avatar asked Nov 26 '25 08:11

tpnsharma


1 Answers

This is possible now in Mongo 3.6 using JSON Schema validation, like so:

db.createCollection("myCollection", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      additionalProperties: false,
      properties: {
        _id: {
          bsonType: 'objectId',
        },
        a: {
          bsonType: "string",
        },
        b: {
          bsonType: "string",
        },
      }
    }
  }
});

Couple notes that might be helpful:

  1. You always have to have an entry for _id when using additionalProperties: false, or every document will fail validation.
  2. If you have nested objects in your schema, you need additionalProperties: false on every bsonType: "object" entry, otherwise that nested object will allow any additional properties on it.

Documentation links:

https://docs.mongodb.com/manual/core/schema-validation/ https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/

like image 50
Allan Wintersieck Avatar answered Dec 03 '25 19:12

Allan Wintersieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!