Mongodb Query based on a column which contains dateTime information

I have a Mongodb collection with event data. it has a column called dateTime. I want to retrieve & export all the data that are after specific date.

Example of data in the dateTime column is as follows.

2022-11-21T15:16:50.029+08:00,

2022-11-21T15:15:57.950+08:00

i tried to retrieve using below commands.

mongo --host=127.0.0.1 --username=admin --password="xxxx" --authenticationDatabase=admin --eval 'db.myevents.find({ "dateTime": { "$gte": { "$date": "2005-11-21T09:58:36.141+08:00" } } }).count()'

Returns 0. But as you can see there are data like the above examples I have provided.

mongoexport --host=127.0.0.1 --username=admin --password="xxxx" --authenticationDatabase=admin --db my_thing  --collection myevents --query '{ "dateTime": { "$gte": { "$date": "2005-11-21T09:58:36.141+08:00" } } }' --out myData.json

Any help is appreciated.

Upvotes: 0

Views: 51

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9294

As discussed in the comments your datatype is a string, to make it work you will need to convert your date strings to date, in the query. This worked for me, locally, you can do something similar:

mongoexport --db=testdb  --collection=myevents --query="{ \"$expr\": { \"$gte\": [{\"$toDate\": \"$datetime\"}, {\"$toDate\": \"2005-11-21T09:58:36.141+08:00\"}]} }

In the query, I am using $expr, and within it I am converting strings to date objects $toDate.

Upvotes: 0

Related Questions