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:
- Incomplete type coverage: You mentioned your field holds either
doubleorintvalues, but yourbsonTypearray only includedlongandint—you need to adddoubleto cover all the actual types in your data. - Missing schema wrapper: MongoDB requires all validation schemas to be wrapped in a top-level
$jsonSchemaobject. 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

