2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MongoDBでコレクションのすべてのフィールドを出力するやり方

Posted at

MongoDBでmongoexportを使ってcsvとして出力する場合、

mongoexport -d dbname -c collectionA -out files.csv --csv --fields field1,filed2, field3

のようにフィールド名を指定しなければなりません。

ドキュメント内のフィールドは固定ではありませんが、CSVのフィールドは固定されているためです。

もしフィールドが沢山あり、そのすべてを出力したい場合どうすればいいのか。

outputCsv.sh
IFS=$IFS;
IFS=",";

dbname="dbname";
user="admin";
password="admin";

keys=`mongo -u $user -p $password  $dbname --eval "rs.slaveOk();var keys = []; for(var key in db.collectionA.findOne()) { keys.push(key); }; keys;" --quiet`;
mongoexport -u $user -p $password --db $dbname --collection collectionA  --fields "$keys" --csv --out file.csv;

IFS=$OIFS;

このスクリプトを実行すれば、すべてのフィールドが出力されます。

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?