MongoDBを使ったプロジェクトに配属されることになったので、勉強がてら一からMongoDBをインストールしてCRUDアプリでも作ろうかなと思いましたが、環境構築でハマりました。
今回はインストール手順解説と共に、ハマった箇所についても考察していきます。
環境
OS:Windows10
インストールツール:Scoop
DB:MongoDB4.4.4
Scoopについて
Scoopとは、Windows用のパッケージ管理ツールです。Linuxを普段お使いの方はyumやaptと同じ認識で良いです。CLIでコマンド一発でアプリケーションをインストール・アンインストール出来るので便利です。
Scoopを使う際の注意点として、ScoopはデフォルトでC:\Users\ユーザー名\scoopにインストールされます。ただ、管理者権限の問題でユーザー名\直下ではなくC:\直下にインストールしたい人は多いでしょう。
その場合はこちらの記事を参考にしてください。
(僕はできなかったのでユーザー名直下にインストールしました)
僕の場合、Scoopでインストールしたアプリケーションは以下のパスにインストールされます。
C:\Users\yuuki\scoop\apps
ですので、MongoDBは以下のパスにインストールされています。
C:\Users\yuuki\scoop\apps\mongodb
ちなみに、インストールしたらshimsってディレクトリ配下にショートカットが入ります。
C:\Users\yuuki\scoop\shims
んで、scoopでは環境変数がC:\Users\yuuki\scoop\shimsに貼られてるので、新しいアプリをインストールしてもわざわざパスを通す必要が無いんですね。
MongoDBのインストール手順
まずはScoopのリポジトリにmongodbがあるか調べてみます。
C:\Users\yuuki>scoop search mongodb
'main' bucket:
mongodb-database-tools (100.3.1)
mongodb (4.4.4)
mongodb (4.4.4)がありますね。最新バージョンのようなので、こちらをインストールします。
C:\Users\yuuki>scoop install mongodb
Updating Scoop...
Updating 'java' bucket...
Updating 'main' bucket...
* 07cf5edd3 omnisharp: Update to version 1.37.8 3 hours ago
* 9cead23a0 omnisharp-http: Update to version 1.37.8 3 hours ago
* 85b34ea63 oh-my-posh3: Update to version 3.125.0 3 hours ago
* 87faba434 mingit: Update to version 2.31.1.windows.1 3 hours ago
* 04bd13221 mingit-busybox: Update to version 2.31.1.windows.1 3 hours ago
Scoop was updated successfully!
Installing 'mongodb' (4.4.4) [64bit]
Loading mongodb-windows-x86_64-4.4.4-signed.msi from cache
Checking hash of mongodb-windows-x86_64-4.4.4-signed.msi ... ok.
Extracting mongodb-windows-x86_64-4.4.4-signed.msi ... done.
Running pre-install script...
Linking ~\scoop\apps\mongodb\current => ~\scoop\apps\mongodb\4.4.4
Creating shim for 'mongo'.
Creating shim for 'mongod'.
Creating shim for 'mongos'.
Persisting bin\mongod.cfg
Persisting data
Persisting log
'mongodb' (4.4.4) was installed successfully!
Notes
-----
Windows server 2012/2008 and Windows 7/8/8.1 need KB2999226 to provide Universal C Runtime support for Windows.
For more infomations, please refer to:
https://support.microsoft.com/en-us/help/2999226/update-for-universal-c-runtime-in-windows
mongod shim use "C:\Users\yuuki\scoop\apps\mongodb\current\bin\mongod.cfg" as the default config file.
To use a different config file, please run
"C:\Users\yuuki\scoop\apps\mongodb\current\bin\mongod.exe --config NEW_CONFIG_FILE"
'mongodb' suggests installing 'extras/vcredist2017'.
インストールできました。
C:\Users\yuuki>scoop list
Installed apps:
dark 3.11.2 [main]
lessmsi 1.8.1 [main]
mongodb 4.4.4 [main]
openjdk11 11.0.2-9 [java]
python 3.9.2 [main]
sbt 1.4.9 [main]
scala 2.13.5 [main]
早速起動してみます。
C:\Users\yuuki>mongo
MongoDB shell version v4.4.4
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: �Ώۂ̃R���s���[�^�[�ɂ���ċ��ۂ��ꂽ���߁A�ڑ��ł��܂���ł����B :
connect@src/mongo/shell/mongo.js:374:17
@(connect):2:6
exception: connect failed
exiting with code 1
はりゃ?いきなり接続失敗。
ググるとどうやら以下のファイルを消すと直るようです。MySQLでも似たような事象あったな・・・。
参考:CentOSでMySQL(MariaDB)をインストールしたがソケットエラーで起動しない問題を解決
/tmp/mongodb-27017.sock
ただ、WindowsのTMPディレクトリ(C:\Users\yuuki\AppData\Local\Temp)配下を探しても、.sockというファイルが見当たらない。
C:\Users\yuuki>echo %TEMP%
C:\Users\yuuki\AppData\Local\Temp
C:\Users\yuuki>dir C:\Users\yuuki\AppData\Local\Temp*.sock
C:\Users\yuuki\AppData\Local のディレクトリ
ファイルが見つかりません
んで、色々調べてみるとそもそもMariaDBサーバーを起動出来ていないことが分かりました。
どうやら、mongoコマンドはMongoDBに接続するためのコマンドで、その前にMongoDBサーバーを起動する「mongod」を打つ必要があるようです。
ちなみに、mongodのdは「デーモン」のdです。Windowsで扱うのにデーモンとは違和感ありますが(Windowsではデーモンのことはサービスと呼んだりするので)、ここではmongod=MongoDBサーバーと解釈します。
早速打ってみます。
C:\Users\yuuki>mongod
Error parsing YAML config file: yaml-cpp: error at line 8, column 11: unknown token
try 'C:\Users\yuuki\scoop\apps\mongodb\current\bin\mongod.exe --help' for more information
Yamlの構成ファイルエラー?configfileに記述ミスがあるってことですか。
というわけで、configfileを探してみた。どうやら以下のパスがconfigfileらしい。中身を開いてみる。
C:\Users\yuuki>"C:\Users\yuuki\scoop\apps\mongodb\4.4.4\bin\mongod.cfg" \configファイルを開く
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: %MONGO_DATA_PATH%
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: %MONGO_LOG_PATH%\mongod.log
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:
なるほど、dbpathとlogpathをセットすればいいんだな?
それっぽいのがあったので設定。(dbpathにはdata直下に作成したdbディレクトリを、logpathにはlog直下に作成したmongod.logファイルのパスを設定)
C:\Users\yuuki>mkdir C:\Users\yuuki\scoop\apps\mongodb\4.4.4\data\db \空のディレクトリ
C:\Users\yuuki>type nul > C:\Users\yuuki\scoop\apps\mongodb\4.4.4\log\mongod.log \空のログファイル作成
C:\Users\yuuki>"C:\Users\yuuki\scoop\apps\mongodb\4.4.4\bin\mongod.cfg" \configファイルを開く
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: C:\Users\yuuki\scoop\apps\mongodb\4.4.4\data\db #dbのパスを指定
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: C:\Users\yuuki\scoop\apps\mongodb\4.4.4\log\mongod.log #logのパスを指定
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
#processManagement:
#security:
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options:
もう一度起動。
C:\Users\yuuki>mongod
反応なしw動いてるのか・・・別のプロンプト立ち上げてmongoコマンドを打ってみる
C:\Users\yuuki>mongo
MongoDB shell version v4.4.4
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("937f2d51-5838-417e-9e98-f5e8e6cb08f5") }
MongoDB server version: 4.4.4
---
The server generated these startup warnings when booting:
2021-03-28T04:49:29.571+09:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
---
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
>
お、動いていたw
db作ってみる
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> use User
switched to db User
> db.User.insert({'name':'yuuki'})
WriteResult({ "nInserted" : 1 })
> show collections
User
> show dbs
User 0.000GB
admin 0.000GB
config 0.000GB
local 0.000GB
> db.User.find()
{ "_id" : ObjectId("605f8e6932f70db2f8a84d56"), "name" : "yuuki" }
大丈夫でした。
Windowsサービスに登録して自動起動をオンにする
最後に、毎回mongd打ってプロンプト立ち上げ直すのは面倒なので、Windows立ち上げ時にMongoDBの自動起動オンになるよう設定します。
調べると、
mongod.exe --config "C:\Users\yuuki\scoop\apps\mongodb\4.4.4\bin\mongod.cfg" --install サービス名
で上手くいくようですが、なぜか–configの部分がエラーとなりヘルプ見てもよくわからなかったので、
最終的に下記のコマンドで対応しました。
mongod --install
上記コマンドでちゃんとWindowsサービスのMongoDBにconfigが入っていました。
(currentというパスになってるけど、実態のディレクトリと同期されてるので問題ないです)

configのdbpath書き換えて再起動したら、ちゃんと指定したdbにデータが入っていたので問題ないでしょう。
これで、自動起動が完了しました!
おまけ:MongoDBCompassも入れてみる
MongoDBのクライアントツールMongoDBCompassも入れてみました。
Scoopでインストールしたら以下のパスに入っています。
"C:\Users\yuuki\scoop\apps\mongodb\4.4.4\bin\InstallCompass.ps1"
作ったコレクションを開いてみました。

すげー見やすい。。。
今後はCompassの使い方にも慣れていこうかと思います^^
MongoDBの環境構築は難しい
スムーズに出来たように見えてますが、実際は苦労しました。
mongod.cfgの記述でlogファイルをディレクトリで指定しちゃったりとか、–dbpathで指定したら起動できたけどそもそもcfg読み込めてないじゃん、ってので色々いじってたら、cfgはC:\data\dbに設定しないとダメだよみたいな情報を発見したり、そもそもC:\data\db にデータを作ることが出来ませんみたいなエラー文が出たので結局cfgじゃdbpath変えられないのかな~とか思ったり(結局ググった情報もエラー文も正しくはありませんでした)、
Windowsサービスへの登録でオプションが効かない部分でも非常に混乱しました
(実際はオプションなしで良かったという、Scoopだったからだと思うが)
あんまりエラー文やググって出た情報は信じすぎない方がいいかもしれませんね。そもそもMongoDBをScoopでインストールするのはイレギュラーなのでそれが難しかった原因かもしれません。。。
この記事がScoopでMongoDBをインストールする時の参考になれば幸いです。