How to convert mongo db json object to csv file

Quickly scribbled a function to get a plain csv out of mongo db json object. Use the script as you would call any shell script.

sh mongo_command.sh > social_data_tmp.csv

The mongo_command.sh has all the required mongo code, Something like –

mongo << EOF
function printUserDetails(user){
if (user == undefined){
return;
}

print(user._id+','+
user.email+','+
user.birthday+','+
((user.homeTown == undefined) ? '' : user.homeTown._id)+','+
cleanString((user.homeTown == undefined) ? '' : user.homeTown.name)+','+
((user.location == undefined) ? '' : user.location._id) +','+
cleanString((user.location == undefined) ? '' : user.location.name)+','+
getNames(user.likes));
}

db.facebookUserData.find().forEach(function(user){
printUserDetails(user);
});

EOF

Leave a Reply

Your email address will not be published. Required fields are marked *