N..
N..

Reputation: 7

mongoexport in python subprocess.call

I am trying to export data from mongo collection into a csv file in python. Below is the code

from pymongo import MongoClient                                            
from subprocess import call      
                            
def mongo_export_to_file():                                                                                                  
    client=MongoClient('mongodb://localhost:27017')                                 
    db=client['mydb']                                                   
    coll=db['data']                                                
                                                                           
    mongo_docs = coll.find()                                             
    if mongo_docs.count() == 0:                                        
        return                                         
                                                        
    fieldnames = list(mongo_docs[0].keys())                                      
    fieldnames.remove('_id')                   
    print(str(fieldnames))                                               
                                                            
    call("mongoexport --uri mongodb://localhost:27017 --db mydb --collection data type csv 
    -- out weather.csv --fields "+str(fieldnames),shell=True)    
                                                                                             
mongo_export_to_file()

i don't want to enter all the column names manually in the --fields
This runs correctly without errors but the csv file is not created. why is it not creating a csv file? What changes should i make?

Upvotes: 0

Views: 439

Answers (1)

Manoa Ny Avo
Manoa Ny Avo

Reputation: 1

Have you tried:

call("mongoexport --uri=mongodb://localhost:27017 --db=mydb
--collection=data --type=csv --out=weather.csv --fields="+','.join(fieldnames))

str(fieldnames) will give you this string value:

"['_id', 'other', 'keys', 'here']"

','.join(fieldnames) gives you this:

_id,other,keys,here

which is the expected input.

By the way I would be more used to --argument=value instead of --argument value

Upvotes: 0

Related Questions