You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB Schema中如何声明支持多种BSON类型的字段?

Let's work through your MongoDB schema validation issue step by step.

Why your initial bsonType array attempt failed

That error (property "numberOf" has invalid type: type [long,int] is not supported) is likely popping up for one of two reasons:

  1. Incomplete type coverage: You mentioned your field holds either double or int values, but your bsonType array only included long and int—you need to add double to cover all the actual types in your data.
  2. Missing schema wrapper: MongoDB requires all validation schemas to be wrapped in a top-level $jsonSchema object. If you skipped this, the server won't interpret your type declaration correctly.

Fixing the numberOf field schema

Since your field stores numeric values spanning int, long, and double, you have two solid options:

Option 1: Explicit BSON type array

This approach directly lists all BSON types you want to allow, and is great if you want to be precise:

{
  "$jsonSchema": {
    "bsonType": "object",
    "properties": {
      "numberOf": {
        "bsonType": ["int", "long", "double"]
      }
    }
  }
}

Option 2: JSON Schema number type

If you just want to allow any numeric value (which covers all your cases), using the standard JSON Schema type: "number" is simpler—all MongoDB numeric BSON types map to this JSON type:

{
  "$jsonSchema": {
    "bsonType": "object",
    "properties": {
      "numberOf": {
        "type": "number"
      }
    }
  }
}

Why your type: "number" try didn't save

Almost certainly, your schema was missing the required $jsonSchema top-level wrapper. MongoDB won't accept a validation schema that isn't nested under this key—think of it as the "magic tag" that tells the server this is a valid JSON Schema definition.

Quick sanity check

When applying the schema via the MongoDB shell, make sure you're using the correct syntax for collection creation or modification:

// Create a new collection with validation
db.createCollection("your_collection_name", {
  validator: {
    $jsonSchema: {
      // Paste your full schema here
    }
  }
})

// Or update an existing collection
db.runCommand({
  collMod: "your_collection_name",
  validator: {
    $jsonSchema: {
      // Your schema here
    }
  }
})

内容的提问来源于stack exchange,提问作者XplosiVe06

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:42:30