Mongoexport using $gt and $lt constraints on a date range

Leah picture Leah · Feb 7, 2013 · Viewed 12.9k times · Source

I am trying to get the orders made for a certain day from my mongodb using the following mongoexport call:

mongoexport --db store --collection user_data --query "{'order.created_order':{$gt:ISODate("2013-02-05T00:00:00.000Z"),$lt:ISODate("2013-02-06T00:00:00.000Z")}, 'order.status':'paid'}" --out ordersfeb6.json

but I am currently experiencing the following error:

Thu Feb  7 18:33:43 Assertion: 10340:Failure parsing JSON string near: 'order.cre
0x56a223 0x5712e5 0x53e0f7 0x53e21e 0x8b7739 0x524f2b 0x5258a3 0x7fa7b77bd76d 0x525975 
mongoexport(_ZN5mongo15printStackTraceERSo+0x23) [0x56a223]
mongoexport(_ZN5mongo11msgassertedEiPKc+0xc5) [0x5712e5]
mongoexport(_ZN5mongo8fromjsonEPKcPi+0x377) [0x53e0f7]
mongoexport(_ZN5mongo8fromjsonERKSs+0xe) [0x53e21e]
mongoexport(_ZN6Export3runEv+0x489) [0x8b7739]
mongoexport(_ZN5mongo4Tool4mainEiPPc+0x72b) [0x524f2b]
mongoexport(main+0x23) [0x5258a3]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed) [0x7fa7b77bd76d]
mongoexport() [0x525975]
assertion: 10340 Failure parsing JSON string near: 'order.cre

From this question mongoexport JSON parsing error I know that javascript is used to evaluate some parts of the mongo queries. I was wondering: do the $gt and $lt operators require javascript and is that my problem? If not, I'm not sure what is wrong with my query and any suggestions would be greatly appreciated. Thank you for reading!

Answer

Adam Comerford picture Adam Comerford · Feb 8, 2013

The issue here is how you are representing the dates, they need to be passed in as Date types and in epoch format. Try this instead:

mongoexport --db store --collection user_data --query '{"order.created_order":{$gt:new Date(1360040400000),$lt:new Date(1360990800000)}, "order.status" : "paid"}' --out ordersfeb6.json

If you are looking to convert ISODate to epoch, just call date in the shell, something like this:

> new Date(2013,01,16)*1
1360990800000

Then to verify:

> new Date(1360990800000)
ISODate("2013-02-16T05:00:00Z")

Update: As noted in the comments by imcaptor, the Month is zero based (0 = Jan, 11 = Dec) in the Date constructor, not something most will expect, and easy to forget. I passed in 01 in the example above and got a February date, as you can see in the ISODate from the verification.