How export a specific query in mongo to csv?

jhonny lopez picture jhonny lopez · Aug 10, 2015 · Viewed 20.8k times · Source

I'm am searching for either on how to export a query result from mongo to CVS or excel, or how to export results in robomongo. I found mongoexport but I think that only can export a collection with some simple constraints.

This is my query:

 db.getCollection('user').find({ "coins": { $elemMatch: { "id":"30","amount":0} }  })

Answer

Jay G picture Jay G · Aug 11, 2015

For MongoDB 3.0+, you can specify the query into mongoexport using -q and --type options:

mongoexport -d test -c user -q '{ coins: { $elemMatch: { "id":"30","amount":0}}}' --type=csv --out exportdir/myRecords.json

For earlier versions, use --csv option with the header fields:

mongoexport -d test -c user -q '{ coins: { $elemMatch: { "id":"30","amount":0}}}' --csv -f first_name,last_name,title --out exportdir/myRecords.json