Let say we have two objects of type NumberInt
in Mongo-Shell:
x = NumberInt(100)
y = NumberInt(100)
when I run the following comparisons, I am wondering why the last comparison is false
?
x == 100 // True
y == 100 // True
x == y // False! Why?
I did however expect to get false
by running the following lines:
x === y // False
x === 100 // False
x === 100 // False
which are false
as expected. Any idea?
2
Answers
The main reason is that equality operators work for primitive values , but not for objects and the function NumberInt() is defining object in the mongoshell:
One option to compare the values in objects is to flatten the values to string via the JSON.stringify() in the mongoshell and then compare:
Note that when you insert the NumberInt(100) object to mongoDB it is converted to integer and if you read it back it is not an object but a number type:
Which mean that if you read the value from mongoDB you can compare with the equality operator without an issue …
I haven’t found exact answer, but I guess the below mostly answers on this question. To understand we can look at
ObjectId
implementation and comparison operators you used.The reason of this behavior is in
equals
implementation that you can see if you simply write a method name without()
:notice that actual comparing happens not with
this
(which is ObjectId) but with some field inside:I think something similar happens with NumberInt as well, I just didn’t find it yet.
Notice2, that it doesn’t affect querying functionality that just simply works: