17

I am using MongoDB with the native node driver and need to accurately store numbers that may be larger than the int maximum 2147483647. I will need to be able to increment the number as I am tracking usage. What are my options?

I am using Mongoose. The problem I am having is that when I $inc past 2147483647 it converts the number to a double. How can I force Mongoose to use the 64-bit long int NumberLong?

My schema looks like this

var schema = new Schema({
    ...
    usedBandwidth: {type: Number, min: 0, default: 0}
});

And my $inc looks like this

model.Account.update(
    {_id: this.account},
    {$inc: {usedBandwidth: this.size}},
    function (err, doc) {}
);
2
  • I just added some more info and code Commented Dec 26, 2011 at 11:46
  • If you need even greater numbers than Double or NumberLong, you may be interested in the NumberDecimal/Decimal128 type. Commented Dec 26, 2023 at 9:05

3 Answers 3

15

You can now do this in Mongoose with the mongoose-long plug-in.

require('mongoose-long')(mongoose);
var SchemaTypes = mongoose.Schema.Types;
var schema = new Schema({
    ...
    usedBandwidth: {type: SchemaTypes.Long, min: 0, default: 0}
});
Sign up to request clarification or add additional context in comments.

1 Comment

How to use this plug-in when you are using es6?
4

MongoDB has a native 64-bit long integer type, usually called NumberLong (at least in the MongoDB javascript shell/driver). If you're using the node-mongodb-native driver, I believe it is just called Long (though I am not certain of this, someone please correct me if I'm wrong). $inc works as expected against fields of type NumberLong.

1 Comment

$inc does not work as expected with Mongoose (note: not Mongo, but Mongoose) for delta values equal to or bigger than 2^31. Then, they suddenly end up being converted to Doubles.
0

If you are sure that your numbers will not be more than [-2^63 to 2^63-1] you will be fine with Long constructor in mogodb (take a look to this article. But keep this into account, bigint in javascript can represent numbers of arbitrary precision, more than Mongo 64bits Long type can represent, so take care if you decide to use bigint in your javascript code.

Anyway, if your numbers could be really big you should prefer string type over Long() constructor in mongodb.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.