忘れそうなので。。。
先人の写経がほとんど
インストール
windows - 公式document
mac - 公式document
説明書
細かい仕様は下のノートが有名です。
英語: The Little MongoDB Book
日本語: MongoDBの薄い本
参考書
windowsの場合下記参考になりました
認証設定や起動、切断に関数事が書いてある
Windows で MongoDB を動かすメモ
macはdocumentのbrew欄を参考
Install MongoDB Community Edition on macOS
起動
設定ファイルは通常以下にある
/usr/local/etc/mongod.conf
そこからログパスも確認してバックエンドで起動する
sudo mongod --fork --dbpath /data/db --logpath /usr/local/var/log/mongodb/mongo.log
コンソール上で起動するなら以下だけでOK
sudo mongod
動かしてみる
mongo
これだけ
CRUD
Database一覧
> show dbs
admin 0.000GB
local 0.000GB
Database作成
> use testDB
switched to db testDB
Database削除
> db.dropDatabase()
{ "dropped" : "testDB", "ok" : 1 }
collection作成
> db.testCollection
testDB.testCollection
collection一覧
> show collections
>
返事がない。。。
insert
> db.testCollection.insert({first_name: 'taro', last_name: 'sato', dob: new Date('2000-01-01'), gender: 'm'})
WriteResult({ "nInserted" : 1 })
> show collections
testCollection
insertした事によって、テーブルcollectionが作成される
ちょっと見てみる
> db.testCollection.find()
{ "_id" : ObjectId("5a1294be8785a7f7da2bd618"), "first_name" : "taro", "last_name" : "sato", "dob" : ISODate("2000-01-01T00:00:00Z"), "gender" : "m" }
update
> db.testCollection.update({"_id" : ObjectId("5a1294be8785a7f7da2bd618")}, {$set: { first_name: "jiro"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.testCollection.find()
{ "_id" : ObjectId("5a1294be8785a7f7da2bd618"), "first_name" : "jiro", "last_name" : "sato", "dob" : ISODate("2000-01-01T00:00:00Z"), "gender" : "m" }
条件指定で検索
> db.testCollection.find({gender: "f"})
>
> db.testCollection.find({gender: "m"})
{ "_id" : ObjectId("5a1294be8785a7f7da2bd618"), "first_name" : "jiro", "last_name" : "sato", "dob" : ISODate("2000-01-01T00:00:00Z"), "gender" : "m" }
条件のオプションは以下
演算子 | 意味 |
---|---|
$lt | 未満 |
$lte | 以下 |
$gt | より大きい |
$gte | 以上 |
$ne | 否定 |
data削除
> db.testCollection.remove({ "_id" : ObjectId("5a1294be8785a7f7da2bd618")})
WriteResult({ "nRemoved" : 1 })
> db.testCollection.find()
>
collection削除
> db.testCollection.drop()
true
> show collections
>
mongoサーバー停止
> db.shutdownServer()
server should be down...
db操作終了
> exit
bye