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?
Asya Kamsky :
You can create it via createCollection command or shell helper:\ndb.createCollection(\n "mycollection", \n {validator:{$jsonSchema:{\n "description": "An address similar to http://microformats.org/wiki/h-card",\n "type": "object",\n "properties": {\n "post-office-box": { "type": "string" },\n "extended-address": { "type": "string" },\n "street-address": { "type": "string" },\n "locality": { "type": "string" },\n "region": { "type": "string" },\n "postal-code": { "type": "string" },\n "country-name": { "type": "string" } \n },\n "required": [ "locality", "region", "country-name" ],\n "dependencies": {\n "post-office-box": [ "street-address" ],\n "extended-address": [ "street-address" ]\n } \n }}})\n\nYou 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)",
2020-07-10T19:42:22