How to export collection to CSV in MongoDB?

前端 未结 11 1601
刺人心
刺人心 2020-12-12 11:52

How do you export all the records in a MongoDB collection to a .csv file?

mongoexport --host localhost --db dbname --collection name --type=csv          


        
11条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 12:07

    If you want, you can export all collections to csv without specifying --fields (will export all fields).

    From http://drzon.net/export-mongodb-collections-to-csv-without-specifying-fields/ run this bash script

    OIFS=$IFS;
    IFS=",";
    
    # fill in your details here
    dbname=DBNAME
    user=USERNAME
    pass=PASSWORD
    host=HOSTNAME:PORT
    
    # first get all collections in the database
    collections=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();db.getCollectionNames();"`;
    collections=`mongo $dbname --eval "rs.slaveOk();db.getCollectionNames();"`;
    collectionArray=($collections);
    
    # for each collection
    for ((i=0; i<${#collectionArray[@]}; ++i));
    do
        echo 'exporting collection' ${collectionArray[$i]}
        # get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
        keys=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();var keys = []; for(var key in db.${collectionArray[$i]}.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
        # now use mongoexport with the set of keys to export the collection to csv
        mongoexport --host $host -u $user -p $pass -d $dbname -c ${collectionArray[$i]} --fields "$keys" --csv --out $dbname.${collectionArray[$i]}.csv;
    done
    
    IFS=$OIFS;
    

提交回复
热议问题