export or write to csv in MongoDB


mongoexport can be run from a shell to export entire database or a collection(table) or a few fields( columns) to a csv file.

You may also mention the query/where condition

ex: mongoexport -h localhost -d databse -c collection --csv
--fields erpNum,orderId,time,status
-q '{"time":{"$gt":1438275600000}, "status":{"$ne" :"Cancelled"}}'
--out export.csv


other option is to run a javascript to write to a csv file.


export.js script is as below :-
print("name,id,email");
db.User.find().forEach(function(user){
  print(user.name+","+user._id.valueOf()+","+user.email);
});

it can be run on the server as below :-
mongo -h localhost -d databse -c collection export.js > out.csv

You can execute a .js file from within the mongo shell, using the load() function, as in the following:

load("scripts/export.js")
load("/data/db/scripts/export.js")

No comments:

Post a Comment