28
16

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基礎:DB接続の書き方

Last updated at Posted at 2019-09-21

はじめに

MongoDBのDBへの接続する書き方はマニュアルにありますけど、たまに注意しないでエラーになる場合があります。

エラー例

1. サービス起動していない OR 起動したMongoDBのIPがlocalhostではなく別サーバ

Error when connecting to the databaseMongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

2. database名の後ろに余分な「/」が付けている

Error when connecting to the databaseMongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoError: Invalid database name: 'mydb/']

3. 認証がある場合、認証DBを指定していない

Error when connecting to the databaseMongoNetworkError: failed to connect to server [10.0.87.26:27017] on first connect [MongoError: Authentication failed.]

4. クラスターの場合、replicaset名不正か、そもそもクラスターが異常がある

Error when connecting to the databaseMongoError: no primary found in replicaset or invalid replica set name

書き方

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]

サンプル

localhost

mongodb://localhost:27017

DB指定

mongodb://localhost:27017/mydb

認証あり(adminデータベースで認証)

mongodb://user:password@localhost:27017/?authSource=admin

replicaSetあり(set名:dbs)

mongodb://IP1:27017,IP2:27017,IP3:27017/?replicaSet=dbs

認証 + replicaSet

mongodb://user:password@IP1:27017,IP2:27017,IP3:27017/?replicaSet=dbs&authSource=admin

など
ほかのパラメータもいろいろ制御できます。

マニュアルURL: https://docs.mongodb.com/manual/reference/connection-string/

以上

28
16
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
28
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?