MongoDB Compass : can't filter a specific ID

Viewed 763

I have a MongoDB Collection build like this :

Screen 1

When I try to filter by ID, I got inconsistent results. For exemple, when I try to get the first entry, by typing in filter query :

{_id:209383449381830657}

I got no result found. enter image description here

But if I type for exemple the third, It work correctly.

{_id:191312485326913536}

enter image description here

I searched if it's due to too large int but no, all _id value are Int64 and it's the same code that generate all entries.

I really don't know why I got this result and that why I am asking here.

EDIT:

  • All entries have same type.
  • No limit are set in query.
  • If I type {_id:{"$gte":209383449381830657}} it found the entry, but don't if I type {_id:{"$eq":209383449381830657}}
3 Answers

MongoDB Compass uses mongo's node.js driver.

Both 209383449381830657 and 191312485326913536 exceed the javascript max safe integer of (2^53-1).

Javascript does not handle numbers larger than that in a consistent manner.

Note that in your documents, those numbers are reported as $numberLong, indicating that they are not using javascript's default floating point numeric representation.

To query these number consistently, use the NumberLong constructor when querying, like

{_id:NumberLong("209383449381830657")}

It depends on the version of MongoDB Compass you have (I assume it's +- latest)

As I see, you are using NumberLong for _id field.

You might use NumberLong("...") to handle such fields in MongoDB.

So, better to try search like this

{_id: NumberLong("209383449381830657")}

Can't say for sure how MongoDB Compass handles number you are trying to pass here. As it should automatically cast values to int32 or int64, but it might be a bit tricky. So, better to define it by yourself to avoid unexpected results.

Some time ago I read an article that it tries to cast to int32, but if it's more than int32 might handle -> then it uses this function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger and tries to cast it to int64. My speculation is that problem lives here, but can't say for sure.

In my case the _id contain hex digits. Filter {_id: ObjectId("62470af3036b9f058552032e")} works

Related