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

后端 未结 8 411
悲哀的现实
悲哀的现实 2021-01-30 10:45

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.

相关标签:
8条回答
  • 2021-01-30 10:47

    In MongoDB 3.2, we can use --queryFile option with mongodump.

    first of all, create a json file:

    //query.json
    {"serverTime": {"$gte": ISODate("2016-01-30T16:00:00.000Z"), "$lt": ISODate("2016-01-31T16:00:00.000Z")}}
    

    next,use mongodump:

    mongodump --db <dbName> --collection <collectionName> --queryFile query.json
    

    simple and clear.

    0 讨论(0)
  • 2021-01-30 10:52

    This should work, what didn't work about your $date query? :

    mongodump --query  {"ts":{$gt:{$date:178929000}}}
    
    0 讨论(0)
  • 2021-01-30 10:55

    Extended JSON Format works, as can be found in the documentation (https://docs.mongodb.com/database-tools/mongodump/). Example:

    --query '{ "timest": { "$gte": { "$date": "2020-08-19T00:00:00.000Z" } } }'

    0 讨论(0)
  • 2021-01-30 10:57

    use single quotes around the query. I found that ISODate() doesn't work.

    mongodump --query  '{"ts":{$gt:{$date:178929000}}}'
    
    0 讨论(0)
  • 2021-01-30 11:04

    Edit: fixed typos

    Add an update:

    1. mongodump --query doesn't support IsoDate, but accepts Date in milliseconds form.

    2. As date command behaves different in OS X, date -d 2011-08-10 +%s does not work for me. If you've run into the same issue, try to read the manual or use this:

      • Get current time in seconds:

        date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"
        
      • Get specific time in seconds:

        date -j -f "%Y-%m-%d %H:%M:%S" "2014-01-01 00:00:00"  "+%s"
        
    3. Use the single quote version to avoid escaping.

      mongodump --query '{updated_at: { $gte: Date(1403280000000) } }'
      
    0 讨论(0)
  • 2021-01-30 11:05

    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}}}"
    
    0 讨论(0)
提交回复
热议问题