Creating unique index in MongoDB with type integer

Viewed 132

I want to create a simple collection that stores statistics of different devices. Each device has a unique device id. I want to enforce the uniqueness so I thought to create a unique index for the device id field, But I didn't figured how to tell the collection that this field is of type number.

For example I can receive query with device id '0x3f', '0x0003f', '3f'... and all of them need to match to the same document. I can parse the request before querying the DB but to me it's not sound like the right solution...

1 Answers

I suggest not worrying about this in Mongo, but instead trying to handle it in your application layer which is calling Mongo. For example, in JavaScript, appreciate that using any hex literal translates to the same integer value:

var i = 0x3f;
var j = 0x0003f;

if (i == 63) {
    console.log("0x3f = 63");
}
if (j == 63) {
    console.log("0x0003f = 63");
}

That is, just let the application marshall the hex literal into an integer value, then pass that int value to Mongo.

Related