mongoexport error – is not a valid JSON query
Issue Description
Executing mongoexport CLI utility gives the below error,
error validating settings: query ” is not valid JSON: invalid character ‘2’ after top-level value
Resolution
mongoexport
is a CLI *command-line interface) a tool that creates a JSON or CSV export of data stored in a MongoDB database.
It’s important to run this command from the system command line and not from the mongo shell.
While using mongoexport , please follow the below guidelines while using the –query option in the commands.
- Mongoexport requires a query option to send the query as a JSON document i.e query with enclosed documents.
- The query must be in Extended JSON v2 format ie. either relaxed or canonical/strict mode with enclosing the field names and operators in quotes:
Considering I had below sample query to be run with export commands,
'{"DateAdded":{"$gt":ISODate('2022-01-01T00:00:00.000+00:00')}}'
while using the above query, I got the below error,
mongoexport.exe –uri=mongodb://xxxx:27017/TheCodeBuzz?readPreference=primary -q ‘{“DateAdded”:{“$gt”:ISODate(‘2022-01-01T00:00:00.000+00:00′)}}’ –out=C://opt/test6.csv –type=csv –collection=Books –fields=UserId,DateAdded
2022-11-27T16:38:27.330-0500 WARNING: ignoring unsupported URI parameter ‘readpreference’
2022-11-27T16:38:29.385-0500 error validating settings: query ‘[39 123 68 97 116 101 65 100 100 101 100 58 123 36 103 116 58 73 83 79 68 97 116 101 40 39 50 48 50 50 45 48 49 45 48 49 84 48 48 58 48 48 58 48 48 46 48 48 48 43 48 48 58 48 48 39 41 125 125 39]’ is not valid JSON: invalid character ‘2’ after top-level value
2022-11-27T16:38:29.385-0500 try ‘mongoexport –help’ for more information
I was able to resolve the issue below two approaches,
Approach 1
I was able to fix the issue by swapping the double quotes as below,
"{'DateAdded':{'$gt':ISODate('2022-01-01T00:00:00.000+00:00')}}"
Approach 2
I was also able to run all complex queries using double quotes as below,
"{\"DateAdded\":{\"$gt\":ISODate('2022-01-01T00:00:00.000+00:00')}}"
Using either of the above approaches results were successful,
That’s all! Happy coding!
Does this help you fix your issue?
Do you have any better solutions or suggestions? Please sound off your comments below.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.