Configure Mongo shell to store all numbers as integers by default

483 Views Asked by At

By default, the MongoDB shell interprets all numbers as floats; this is a problem when trying to convert existing JSON formatted data (stored as strings in Mongo) to actual Mongo BSON objects. It would also be tedious to explicitly and manually wrap any integer values in the data with NumberInt(...)/NumberLong(...) because integers can occur anywhere in the data.

Is there a way to configure one MongoDB shell session to use NumberInt or NumberLong by default?

Alternatively: is there a way to parse a string of JSON into an object in the MongoDB shell so that all numbers without decimal points are already wrapped with NumberInt/NumberLong?

1

There are 1 best solutions below

0
On BEST ANSWER

The solution I ended up using for now is calling a markIntegers function on the data returned from JSON.parse; it seems to be working fine. I'm posting it here for completeness' sake; better solutions and corrections are very welcome!

function markIntegers(obj) {
    if (obj instanceof Array) {
        return obj.map(function(x) { return markIntegers(x); });
    // make sure it's a plain object and not Date or BinData etc
    } if (obj !== null && typeof obj === "object" && obj.constructor === Object) {
        var ret = {}
        for (var key in obj)
            ret[key] = markIntegers(obj[key]);
        return ret;
    } else if (typeof obj === "number") {
        return obj === Math.floor(obj) ? NumberLong(obj) : obj;
    } else {
        return obj;
    }
}

which works like this:

> markIntegers({a: {b: 3}, c: 4.4, e: ["hello"]})
{ "a" : { "b" : NumberLong(3) }, "c" : 4.4, "e" : [ "hello" ] }