首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建具有标准JSON架构的MongoDB集合

创建具有标准JSON架构的MongoDB集合
EN

Stack Overflow用户
提问于 2020-05-26 22:03:37
回答 2查看 1.6K关注 0票数 3

我想使用JSON schema文件创建一个MongoDB集合。

假设JSON文件address.schema.json包含地址信息模式(this file is one of the Json-schema.org's examples):

代码语言:javascript
复制
{
  "$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命令是什么,比如mongoimportdb.createCollection

如果我可以在MongoDB中直接使用文件,而不需要手动更改文件格式,那就太好了。

我想知道JSON schema格式是否是标准格式,为什么我需要将其更改为适用于MongoDB。为什么MongoDB没有内置此功能?

EN

回答 2

Stack Overflow用户

发布于 2020-07-11 03:42:23

您可以通过createCollection命令或shell helper创建它:

代码语言:javascript
复制
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)不支持这两行。

票数 1
EN

Stack Overflow用户

发布于 2020-05-26 22:15:53

您可以使用的惟一选项是在创建集合时添加jsonSchema验证器:https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/#document-validator。这意味着您要在集合中插入/更新的任何文档都必须与提供的架构匹配

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62023945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档