MongoDB のデータエクスポート方法
MongoDB のデータをエクスポートするには、以下のような方法があります。
- mongodumpコマンドを使用して、データベース全体や特定のコレクションのデータをBSONファイル形式でエクスポートできます。例えば、以下のコマンドを使用してデータベース全体をエクスポートします。
mongodump --db <database_name> --out <output_directory>
指定コレクションを以下のコマンドでエクスポート
mongodump --db <database_name> --collection <collection_name> --out <output_directory>
- mongoexportコマンドを使用して、コレクションのデータをCSV、JSON、TSV形式でエクスポートできます。例えば、下記のコマンドでは指定されたコレクションのデータをJSON形式でエクスポートします。
mongoexport --db <database_name> --collection <collection_name> --out <output_file.json>
- 言語ごとの MongoDB ドライバを使用: MongoDB ドライバは通常、データをエクスポートするための API を提供しています。たとえば、Python の pymongo ライブラリを使用すると、次のコードで指定されたコレクションのデータを JSON 形式でエクスポートできます。
from pymongo import MongoClient
import json
client = MongoClient()
db = client[<database_name>]
collection = db[<collection_name>]
cursor = collection.find()
with open('<output_file.json>', 'w') as f:
for document in cursor:
json.dump(document, f)
f.write('\n')
- サードパーティ製ツールを利用:MongoDB Compass、Studio 3T などのサードパーティ製ツールを利用して MongoDB データをエクスポートすることもできます。これらのツールは、通常、グラフィカル ユーザー インターフェイスを提供し、データ エクスポート向けにカスタマイズ可能なオプションを豊富に備えています。