21

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?

Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83

3 Answers3

40

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}"
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
18

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).

rowanu
  • 1,683
  • 16
  • 22
  • @rowanu: Hey, is this possible for group by queries? – Shashank Nov 18 '13 at 09:03
  • 1
    The solution by @rowanu doesn't works for me, but this one does: `--query '{ $query: {}, $orderby: {count: -1} }' --forceTableScan` – hennadiy.verkh Jan 24 '14 at 15:19
  • Yeah, my solution is nearly two years old, and was done on MongoDB version 2.0 (current stable version is 2.4, with 2.6 coming out soon) so that's not surprising. – rowanu Jan 25 '14 at 01:24
  • Not sure if that bug was fixed - see [this issue I filed](https://jira.mongodb.org/browse/SERVER-12665). – Dan Dascalescu Feb 10 '14 at 07:48
  • orderBy was deprecated. see here: https://stackoverflow.com/a/48051096/5986661 and https://docs.mongodb.com/manual/reference/operator/meta/orderby/ – Omkar Neogi Jun 07 '19 at 15:57
-9

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.

Barrie
  • 811
  • 6
  • 6