Node.js date filtering in collection.find()

I run the following in Atlas:

{
  _timestamp: {
    $gt: {
      $date: "2023-06-18T00:00:00.0000Z",
    },
  },
}

And it happily returns what i want.
When I run the same inside a collection.find() inside of Node, i get no results in my cursor. I have run without the filter to confirm everything is working. I’ve copied the query directly from Node to Atlas as well to confirm there are no differences and experimented quite a bit to get to the above after reading many forum posts that didn’t work (e.g. using new Date()). The data I am querying against is a date field not a string (and hence it works fine from Atlas). Any ideas? I’m sure I’m doing something stupid, but I’m not sure what stupid thing I’m doing.

The stupid thing most often made is using the wrong server, the wrong database or the wrong collection.

I appreciate that, but already checked that a few times. I can confirm it is the same database, same collection, when i remove the filter all of the data flows as expected, if i copy the filter over to the mongo ui and apply it filters properly/if i do it in node it returns no results.

Please share the code you tried

Hah, son of a gun. Now it is working with the new Date() syntax. Sorry for the bother

1 Like

Hi @michael_hyman1

Glad you resolved the issue.

I may have an idea why it’s working. In Atlas, it recognizes the extended JSON date format (the one using $date: <ISODate> in your earlier example). However Node doesn’t recognize this, and the only way to create a datetime variable is to use new Date(<ISODate>).

I think this is why the earlier extended JSON $date doesn’t work in Node. It was literally searching for sub-documents that looks like {$date: <ISODate>} instead of a datetime datatype.

Best regards
Kevin

1 Like

Fascinating. That makes a ton of sense and it feels good to have a sense of the reason.
I have to say, Mongo has been a blast to work with even though I’m just touching the surface.

1 Like