LoginSignup
0
0

More than 1 year has passed since last update.

mongodbにデータインポート

Posted at

背景

js勉強中mongodbを触ろうと思い、折角だからコンテナでと思い、、

dockerでmongodbコンテナ作成

コンテナの中に入りmongoimportコマンドでjsonファイルをインポート

ホストPC:Windows11

WSL2:Ubuntu20.04.4

コンテナ化

使用イメージ:mongodb/mongodb-community-server

https://hub.docker.com/r/mongodb/mongodb-community-server

コンテナ起動方法は公式参照

https://www.mongodb.com/docs/manual/tutorial/install-mongodb-community-with-docker/

ユーザ名(MONGO_INITDB_ROOT_USERNAME)やパスワード(MONGO_INITDB_ROOT_PASSWOR)はコンテナ起動時に環境変数として渡してください。

ホストポートは適当に開けてください。

docker desktopを使用した場合、コンテナ起動時にOptional Settingをクリックすることで

ストレージ共有や環境変数も設定できます。

普段コマンドなのでdocker desktopが使いやすくてびっくりしました。。。

Untitleda.png

これでホストにインストールしたmongo compassからコンテナに接続。

Untitled.png

GUIでdbやコレクションを作って、データをインポートもできます。

コマンドでデータをインポート

ホストPCにデータがあるのでコンテナに移す。

docker cp <ホストパス> <コンテナID>:<コンテナ内パス>

ex)
docker cp /share/test.json 4tc06fe07dne:/data/

mongodbコンテナ内に入り、mongoimportコマンドでインポート

コマンド詳細は

https://www.mongodb.com/docs/database-tools/mongoimport

mongoimport --authenticationDatabase admin  -u user -p pass --db bookshelf --collection books --file /data/books.json --jsonArray

Error

データインポート時の認証エラー

ユーザ管理者でMongoDBに接続する場合、--authenticationDatabase adminが必要。

あとユーザとパスワードも。

http://ittoo.jugem.jp/?eid=841

なかったら以下のエラーが出る。

error connecting to host: could not connect to server: connection() error occurred during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.

データインポート時のデータ形式エラー

インポートしようとしていたデータは以下。

[
	{
    "id": {
      "$oid": ""
    },
    "title": "",
    "description": "",
    "rating": ,
    "comment": "",
    "createdAt": {
      "$date": {
        "$numberLong": ""
      }
    },
    "updatedAt": {
      "$date": {
        "$numberLong": ""
      }
    },
    "__v": 
  },
	{
	
	},
~省略~
	{

	}
]

mongoimportコマンドはデフォルトでドキュメントが配列に含まれていないことを想定しているので、私がインポートしようとしていたデータは配列に含まれているデータなので

—jsonArrayパラメータが必要でした。

https://www.reddit.com/r/mongodb/comments/wshjrd/importing_a_json_array_error_failed_cannot_decode/

なかったら、以下のようなエラーが出ました。

Failed: cannot decode array into a primitive.D
0
0
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
0
0