我想使用JSON schema文件创建一个MongoDB集合。
假设JSON文件address.schema.json包含地址信息模式(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" ]
}
}使用上面的模式创建MongoDB集合的MongoDB命令是什么,比如mongoimport或db.createCollection?
如果我可以在MongoDB中直接使用文件,而不需要手动更改文件格式,那就太好了。
我想知道JSON schema格式是否是标准格式,为什么我需要将其更改为适用于MongoDB。为什么MongoDB没有内置此功能?
发布于 2020-07-11 03:42:23
您可以通过createCollection命令或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" ]
}
}}})如果要使用存在于bson中但不存在于通用json模式中的类型,则只需指定bsonType而不是type。您必须删除$id和$schema行,因为MongoDB JSON schema support (documented here)不支持这两行。
发布于 2020-05-26 22:15:53
您可以使用的惟一选项是在创建集合时添加jsonSchema验证器:https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/#document-validator。这意味着您要在集合中插入/更新的任何文档都必须与提供的架构匹配
https://stackoverflow.com/questions/62023945
复制相似问题