Exporting MongoDB to CSV

Pretend the business guys want to add user information into the CRM and it needs to be in CSV. Since they only want certain fields and users in good standing we need to do a query on the database and then limit the output to the fields we want using mongoexport.

This is the schema of the data we have in our user collection:

{
"_id" : ObjectId("55f5a5532b1d457c9ba94328"),
"role" : 1, // 1 = mod, 2 = user, 666 = hellban
"name" : "Montana Flynn",
"username" : "anonfunction",
"email" : "montana@montanaflynn.com",
"password" : "$2a$10$0bMPuatCwpsaFeafjvDVgO86n"
}

Since we just need to users who have emails and are not "hellbanned" we can use the --query option with a quoted JSON mongo query. Additionally we must tell mongo which fields to export with the --fields option which takes a comma seperated list in quotes.

mongoexport --db appname --collection users \
--query '{ "$and" : [ { "email" : { "$ne" : "" } }, { "role" : { "$ne" : 666 } } ] }' \
--csv --fields 'name, username, email' --out ./user-emails.csv