LoginSignup
2
1

More than 5 years have passed since last update.

mongoDB インストールから基本操作

Posted at

環境

ubuntu16.04

インストール

// パブリックキーの登録
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

// 利用可能なパッケージ一覧にMongoDBを登録
$ echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

// パッケージの更新
$ sudo apt-get update

// インストール
$ sudo apt-get install mongodb-org

MongoDBの開始と停止

開始

$ sudo service mongod start

停止

$ sudo service mongod stop

再起動

$ sudo service mongod restart

操作

アクセス

$ mongo

DB一覧

$ show dbs

使用するDBの切り替え

$ use [DBの名前]

DBの状況確認

$ db.stats()

DBの削除

$ db.dropDatabase()

collectionの作成

$ db.createCollection("collection名")

collectionの一覧

$ show conllections

collectionの名前変更

$ db.変更するcollection名.renameCollection("新しいcollection名")

collectionの削除

$ db.削除するcollection名.drop()

documentの挿入

$ db.collection名.insert({オブジェエクト})

// 例
$ db.collection名.insert({ name: "hoge", score: 1})

documentの数

$ db.collection名.count()

documentの全件抽出

$ db.collection名.find()

documentの全件削除

$ db.collection名.remove({})

// もしくはコレクションごと削除する
$ db.collection名.drop()

documentの条件付き抽出

公式ドキュメントにいろんな演算子が記載されています。
https://docs.mongodb.com/manual/reference/operator/query/
ちなみに、fieldとは、objectで言う所のkey

ぶん投げ感が強いので、いくつか例を示します。
仮にinventoryというcollectionに、以下のようなdocumentがあったとします。

{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] }
{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] }
{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] }
{ _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] }
{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }

ここからfieldqtyを基準に抽出すると..

// qtyが20に等しいものの抽出
$ db.inventory.find( { qty: { $eq: 20 } } )

// qtyが20以上のものの抽出 
$ db.inventory.find( { qty: { $gte: 20 } } )

正規表現もを使った抽出もできます。
https://docs.mongodb.com/manual/reference/operator/query/regex/#op._S_regex

複数の条件文ももちろん
https://docs.mongodb.com/manual/reference/operator/query/and/#op._S_and
(条件抽出に関しては、内容が多いので次の機会に.)

参考

2
1
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
2
1