MySQL等と互換性のあるファイル形式といえばCSVですね。 これをMongoDBでインポートする方法です。
◆環境
Ubuntu 14.04
MongoDB 2.6.4
◆事前準備
CSVファイルをGETしてきましょう。LINEがデータを提供してくれているのでそれをダウンロードしてきます。
$ git clone https://github.com/livedoor/datasets.git
$ cd datasets/ $ tar xvzf ldgourmet.tar.gz areas.csv categories.csv prefs.csv ratings.csv rating_votes.csv restaurants.csv stations.csv
中身をちょっと確認してみます。
$ head prefs.csv id,name 1,"北海道" 2,"青森県" 3,"岩手県" 4,"宮城県" 5,"秋田県" 6,"山形県" 7,"福島県" 8,"茨城県" 9,"栃木県"
よくある形式でわかりやすいですね。
◆インポート
先ほど確認したファイルをインポートします。
$ mongoimport --db testDB --collection prefs --type csv --file prefs.csv --headerline
各オプションは以下の意味があります。
--db DB名 --collection コレクション名 --type 入力ファイル形式 --file 入力ファイル名 --headerline ヘッダ行のはインポートしない(プロパティ名としては認識される)
MongoDBの中身を確認してみます。
$ mongo > use testDB > db.prefs.find().limit(10) { "_id" : ObjectId("54264e296a3dcee8a40d9491"), "id" : 1, "name" : "北海道" } { "_id" : ObjectId("54264e296a3dcee8a40d9492"), "id" : 2, "name" : "青森県" } { "_id" : ObjectId("54264e296a3dcee8a40d9493"), "id" : 3, "name" : "岩手県" } { "_id" : ObjectId("54264e296a3dcee8a40d9494"), "id" : 4, "name" : "宮城県" } { "_id" : ObjectId("54264e296a3dcee8a40d9495"), "id" : 5, "name" : "秋田県" } { "_id" : ObjectId("54264e296a3dcee8a40d9496"), "id" : 6, "name" : "山形県" } { "_id" : ObjectId("54264e296a3dcee8a40d9497"), "id" : 7, "name" : "福島県" } { "_id" : ObjectId("54264e296a3dcee8a40d9498"), "id" : 8, "name" : "茨城県" } { "_id" : ObjectId("54264e296a3dcee8a40d9499"), "id" : 9, "name" : "栃木県" } { "_id" : ObjectId("54264e296a3dcee8a40d949a"), "id" : 10, "name" : "群馬県" }
プロパティ名もきちんと入っていますね。 以上です。
ソース: