How to Export Sorted Data Using Mongoexport?

How to Export Sorted Data Using Mongoexport?

I have a collection in mongo which has name and count fields.

{name:'myName',count:5}

Is it possible to sort data by count and export as json using mongoexport?

3 Answers

Starting with MongoDB 2.6, you can pass --sort to mongoexport directly:

mongoexport --db mydatabase -c people --fields name,age --sort "{name: 1, age: 1}"

Actually you can, but you have to use special params. Here's a sample (redirecting to file):

$ mongoexport  -q '{ $query: {count: {$gt:0}}, $orderby: {count: -1} }' -d database -c collection > data_dump.json

The $query part is not strictly necessary, but I included it because of this bug on GitHub (fixed now, but only just).

6

You can't pass in an argument to sort your documents by a specific key when using mongoexport.

The way to do this would be to write your own script.

Hope this helps.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.