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

mongoexport error is not valid JSON query

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,

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.



Leave a Reply

Your email address will not be published. Required fields are marked *