$jsonschema integer

I am testing a $jsonSchema. I don’t understand why the bsonType “int” requires the numberInt() function.

Simple validation, where PartId is type int

db.createCollection( "test_val" , { 
   validator: { $jsonSchema: { 
      bsonType: "object" ,
      properties: { 
                    PartId: { bsonType: "int",
                              description :"int required"
                            }
                  }  
          
      }) 

Here I insert an integer (I think?) but it fails.

db.test_val.insertOne({"PartId" : 123})

WriteError({
	"index" : 0,
	"code" : 121,
	"errmsg" : "Document failed validation",
	"op" : {
		"_id" : ObjectId("604c3a16c569f2096c735bed"),
		"PartId" : 123
	}
})

It works with the NumberInt() function.

db.test_val.insertOne({"PartId" : NumberInt(123)})

{
	"acknowledged" : true,
	"insertedId" : ObjectId("604c3a54c569f2096c735bee")
}

Hi @David_Lange,

I think by default the shell turn a number into a decimal.

If you need explicitly int you have to convert it like you have

Thanks
Pavel

Hi @David_Lange,

MongoDB’s internal document representation uses the BSON binary serialisation format which supports standard JSON data types as well as extended types which are not native to JavaScript (for example, 32-bit and 64-bit integers).

JavaScript’s built-in Number type is a double-precision 64-bit binary value which maps to the BSON type of double.

To align your data model with validation you could:

  • Use the NumberInt() wrapper to pass a value as a 32-bit integer in the mongo shell. Drivers also support extended MongoDB type representations but will use naming consistent with the driver API.

  • Change your validator to use the double type to match JavaScript’s default Number type.

  • Change your validator to use the number BSON alias which will match against any numeric type (32-bit integer, 64-bit integer, double, or decimal128).

The number alias provides some flexibility for numeric fields with a range of values that may require different numeric precision.

For example, a 32-bit integer (int32) uses fewer bytes in an uncompressed document than a double or decimal128 value:

BSON Type Size
int32 4 bytes (32-bit signed integer, two’s complement)
int64 8 bytes (64-bit signed integer, two’s complement)
double 8 bytes (64-bit IEEE 754-2008 binary floating point)
decimal128 16 bytes (128-bit IEEE 754-2008 decimal floating point)

Regards,
Stennie

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.