0

Is there any way to perform integer arithmetic on two NumberInt or NumberLongs in MongoDB's mapreduce Javascript or in the shell? As you see, I get:

> typeof (NumberInt(1) + NumberInt(1))
number

# (and this is here sort of just to gripe)
> NumberLong(2) == NumberInt(2)
false
> 2==NumberLong(2)
true
> 2==NumberInt(2)
true

Relevant:

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Scott Stafford
  • 43,764
  • 28
  • 129
  • 177
  • typeof is not arithmetic – Sammaye Mar 26 '14 at 19:09
  • Sorry for the confusion. `1+1` is the arithmetic. `typeof` just shows us that the returned value is `number` and not `NumberInt`. – Scott Stafford Mar 26 '14 at 19:19
  • I have been looking around a bit and even converting to native JS isn't a good way to go since you can loose precision on big ints, not sure how much of a choice you have in JS alone – Sammaye Mar 26 '14 at 19:29
  • look at this post: http://stackoverflow.com/questions/8592825/numberlong-arithmetic-in-the-mongo-shell – innoSPG Mar 26 '14 at 22:31

1 Answers1

1

Since these are actually objects, use their methods:

var num1 = NumberLong(2);
var num2 = NumberInt(2);

num1.toNumber() == num2.toNumber()

Which will return true. And in the same way:

var num1 = NumberLong(2);
var num2 = NumberInt(3);

num1.toNumber() == num2.toNumber()

Returns false as they are not equal:

num1.toNumber() < num2.toNumber()

Is also valid as true

So you basically need to use the method to do the casting in this way.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • That does not solve the arithmetic issue. I still cannot do integer-space arithmetic. – Scott Stafford Mar 28 '14 at 13:14
  • @ScottStafford Not sure what you are talking about as your question does not even make this point clear. Perhaps expand on what you wish to do. If you are talking about "adding" the value of a "Long" to an "Int" then if you **tried** this with the methods I used then you would see that it works. – Neil Lunn Mar 28 '14 at 13:31
  • Yes, `NumberLong(2).toNumber() + NumberInt(2).toNumber()` will result in 4. But the Javascript `number` is a double. So if you try doing the same thing with very large integers it will start rounding them. See http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-t for instance. My question is about getting mongo db to integer arithmetic, which will not round, instead of floating-point arithmetic. – Scott Stafford Mar 31 '14 at 21:41