Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use mongodump to dump out records matching a specific date range?

Tags:

mongodb

I'm trying to use the mongodump command to dump out a bunch of records created on a specific date. The records include a "ts" field which is a MongoDB Date() object.

mongodump takes a -q argument which can be used to run a query to select the records to be included in the dump. Unfortunately, the -q argument needs to be provided in JSON, and it's not clear how to express a "less-than-this-date, more-than-this-date" query in pure JSON (normally such queries would use a 'new Date()' constructor)"

Any tips? I've tried using the {$date: unix-timestamp-in-milliseconds} format but it's not working for me.

like image 703
Simon Willison Avatar asked Aug 09 '11 13:08

Simon Willison


People also ask

What does Mongodump command do?

The mongodump is a utility for creating database backups. The utility can be used for creating binary export of the database contents. Mongodump can export data from both mongod and mongos instances, allowing you to create backups from: A standalone, replica set.

Does Mongodump include index?

Yes, mongodump does export the indexes created on the collection, and the indexes are restored with mongorestore along with the data.

Does Mongodump lock the database?

Mongdump does not lock the db. It means other read and write operations will continue normally.


2 Answers

I solved it - the magic incantation I was looking for is:

mongodump --query "{\"ts\":{\"\$gt\":{\"\$date\":`date -d 2011-08-10 +%s`000},\"\$lte\":{\"\$date\":`date -d 2011-08-11 +%s`000}}}" 
like image 145
Simon Willison Avatar answered Sep 17 '22 00:09

Simon Willison


A more human-readable version than @SimonWillison's escaped version:

--query "{ time: { \$gt: new Date(1312959600000), \$lt: new Date(1313046000000) }}"

(Note the dollarsigns still need to be escaped.)

I got the millisecond timestamps by creating dates in the shell, e.g.:

> var targetDateStart = new Date(2011, 7, 10); > var targetDateEnd = new Date(2011, 7, 11); > targetDateStart.getTime(); 1312959600000 > targetDateEnd.getTime(); 1313046000000 
like image 42
ericsoco Avatar answered Sep 17 '22 00:09

ericsoco