Create MongoDB collection with standard JSON schema

Viewed 2922

I want to create a MongoDB collection using an JSON schema file.

Suppose the JSON file address.schema.json contain address information schema (this file is one of the Json-schema.org's examples):

{
  "$id": "https://example.com/address.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "description": "An address similar to http://microformats.org/wiki/h-card",
  "type": "object",
  "properties": {
    "post-office-box": {
      "type": "string"
    },
    "extended-address": {
      "type": "string"
    },
    "street-address": {
      "type": "string"
    },
    "locality": {
      "type": "string"
    },
    "region": {
      "type": "string"
    },
    "postal-code": {
      "type": "string"
    },
    "country-name": {
      "type": "string"
    }
  },
  "required": [ "locality", "region", "country-name" ],
  "dependencies": {
    "post-office-box": [ "street-address" ],
    "extended-address": [ "street-address" ]
  }
}

What is the MongoDB command, such as mongoimport or db.createCollection to create a MongoDB collection using the above schema?

It can be nice if I can use the file directly in MongoDB with the need of changing the file format manually.

I wonder if the JSON schema format is a standard one, why do I need to change it to adopt it for MongoDB. Why MongoDB does not have this functionality built-in?

2 Answers

You can create it via createCollection command or shell helper:

db.createCollection(
    "mycollection", 
    {validator:{$jsonSchema:{
        "description": "An address similar to http://microformats.org/wiki/h-card",
        "type": "object",
        "properties": {
           "post-office-box": {       "type": "string"     },
           "extended-address": {       "type": "string"     },
           "street-address": {       "type": "string"     },
           "locality": {       "type": "string"     },
           "region": {       "type": "string"     },
           "postal-code": {       "type": "string"     },
           "country-name": {       "type": "string"     } 
        },
        "required": [ "locality", "region", "country-name" ],
        "dependencies": {
            "post-office-box": [ "street-address" ],
            "extended-address": [ "street-address" ]
        } 
  }}})

You only need to specify bsonType instead of type if you want to use a type that exists in bson but not in generic json schema. You do have to remove the lines $id and $schema as those are not supported by MongoDB JSON schema support (documented here)

Related