使用标准的JSON模式创建MongoDB集合

3

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

假设 JSON 文件 address.schema.json 包含地址信息模式(此文件是 Json-schema.org 的示例之一):

{
  "$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模式格式是否是标准的,为什么我需要更改它才能适应MongoDB。为什么MongoDB没有内置此功能?

2个回答

2
您可以通过createCollection命令或shell助手创建它:
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模式支持不支持这些内容(在此处记录)。


-1

你能否写出问题中示例的完整命令? - Sadegh
我在这方面没有太多经验,但是看了一下文档示例 https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/#schema-validation,你的模式应该有一个稍微不同的格式。 - dododo
是的,格式上的差异让我感到困惑。我想知道JSON模式格式是否是标准格式,为什么我要在MongoDB中更改它。为什么不直接使用它呢? - Sadegh
1
我猜这是因为bsonType不等于jsonType,因此可用选项可能会有所不同。但请参见此处的注释(MongoDB支持JSON模式的草案4):https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/#op._S_jsonSchema。不确定它的意思,但您可以检查一下,也许您的模式也可以工作。 - dododo
我不明白Mongo在传递验证参数时使用的数据类型是什么。BSON是一种二进制格式,不是吗?所以我猜它不是BSONType。看起来像是JSON和BSON的混合体。 - Sadegh
BSON是一种与JSON非常相似的类型(但具有一些附加类型),但在发送到服务器时,此类型将被编码为二进制格式。 - dododo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接