Use mongoexport with a --query for ISODate

我的未来我决定 提交于 2020-03-13 06:08:26

问题


I have this query but i´m getting a syntax error: unexpected identifier

mongoexport --db ium --collection events \
  --query 'db.events.find({'created_at' : {
      $gte: ISODate("2016-03-01T00:00:00.001Z"),
      $lte: ISODate("2016-03-29T23:59:59:59.000Z")
    }, 
    "name" : "UPDATE_SUCCESS"})' \
 --out guille1_test.json

what can it be wrong?


回答1:


You need to use "extended json" in queries with mongoexport. So the way to specify "dates" is with $date instead. And the --query is just the "query string" in JSON format. Not the whole command entered into the shell:

mongoexport --db ium --collection events \
  --query '{ 
    "created_at": { 
      "$gte": { "$date": "2016-03-01T00:00:00.001Z" },
      "$lte": { "$date": "2016-03-29T23:59:59.000Z" }
    },
    "name": "UPDATE_SUCCESS"
  }' \
  --out guile1_test.json

Note also the corrected date string in the $lte argument and of course the "quoting" use of '' around the body of the JSON argument and "" around the internal expressions and values. It s important that these types of quotes are different, as well as "shell arguments" should have their "outer" quotes as '', otherwise the "shell" tries to evaluate the expression contained.




回答2:


Another working solution is by using the new Date() constructor as described in the MongoDB manual. This will result in a smaller query body footprint like so:

    mongoexport --db ium --collection events \
  --query '{ 
    "created_at": { 
      "$gte": new Date("2016-03-01T00:00:00.001Z"),
      "$lte": new Date("2016-03-29T23:59:59.000Z")
    },
    "name": "UPDATE_SUCCESS"
  }' \
  --out guile1_test.json

This approach worked for me out-of-the-box while all other alternatives failed. There is a relative article describing this approach here.




回答3:


Best way to achieve it as following. Because new Date and IOSDate would be invalid literal for this command.

For remote host

mongoexport --host {{host}} --username {{username}} --password {{passord}} --authenticationDatabase admin --db {{Database}} --collection {{collection Name}} --query '{ "date" : { "$gt" : {"$date":"2019-10-31T00:00:00.000Z"}  } }'  --type json --out {{path of directory where you would want to export file.}}

For local host

 mongoexport  --db {{Database}} --collection {{collection Name}} --query '{ "date" : { "$gt" : {"$date":"2019-10-31T00:00:00.000Z"}  } }'  --type json --out {{path of directory where you would want to export file.}}


来源:https://stackoverflow.com/questions/36319052/use-mongoexport-with-a-query-for-isodate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!