Search code examples
mongodbdateaggregation-frameworkmongoexportisodate

Export subset of a collection base on a Date in MongoDB


I am trying to export data from mongoDB

mongoexport -d MY_DB_NAME -u DB_USER -p _REDACTED_ -c person \
-q "{ '$and':[ { 'hasActiveAck':{ '$ne':false }}, { 'creationDate':{'$gte': new Date(1506816000),  '$lte': new Date(1509404400)} }]}" \
--fields '_id,email' --type=csv --out people_oct.json

The problem is that this extracts 0 rows

If I call this query

db.getCollection('person') 
.find({  
$and:[  
  {  
     hasActiveAck:{  
        $ne:false
     }
  },
  {  
    creationDate:{ 
        $gte:new Date(1506816000) ,
        $lte:new Date(1509408000)
        }
  }
 ]
 }).count();

the result is 0 rows

But if I run the query with ISODate instead of Date like this:

db.getCollection('person') 
.find({  
$and:[  
  {  
     hasActiveAck:{  
        $ne:false
     }
  },
  {  
    creationDate:{ 
        $gte:ISODate("2017-10-01T00:00:00.000Z") ,
        $lte:ISODate("2017-10-31T00:00:00.000Z")
        }
  }
  ]
  }).count();

The result is 58k+ rows

What am I doing wrong?

Some details:

mongoexport --version

mongoexport version: r3.2.11
git version: 45418a84270bd822db0d6d0c37a0264efb0e86d2
Go version: go1.7
 os: linux
 arch: amd64
 compiler: gc
OpenSSL version: OpenSSL 1.0.1f 6 Jan 2014

mongo --version

MongoDB shell version: 3.0.14

mongod --version

db version v3.0.14

Solution

  • The Date constructor takes the number of milliseconds, not seconds.

    new Date(1506816000).toISOString()
    "1970-01-18T10:33:36.000Z"
    
    new Date(1506816000000).toISOString()
    "2017-10-01T00:00:00.000Z"
    

    Integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider that most Unix timestamp functions count in seconds).