Mongo DBのデータ階層
Database -> collection -> document
MySQLだと、下記の構成になる
Database(schema) -> table -> row
接続
- localhostにユーザ認証せずに接続
$ mongo
MongoDB shell version v3.4.15
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.15
Server has startup warnings:
>
- 接続時にメッセージを出さない(パイプでつなぐ時にベンリ)
mongo --quiet
- localhostの特定DBに繋いだ形で開始
mongo db_name
- 非対話で検索
```language-bash
mongo db_name --eval 'db.collection1.count();'
- 非対話でshowコマンドを実行
showコマンドの場合は--evalではなく標準入力から流し込む
echo 'show collections;' | mongo db_name --quiet
操作方法
- 全体の操作
# DBの一覧を見る
> show dbs
db1 0.000GB
db2 0.001GB
db3 0.342GB
# DBを選択
> use db1
switched to db db1
# コレクション(テーブルのような物)の一覧を見る
> show collections
collection1
collection2
collection3
collection4
dbの作成
- create database db_test;
useしてからcollectionを追加するとDB自体が自動生成されるので、明示的なcrete databaseは無い
use db_test
db.test1.insert({ id: 1, name : "alice", })
コレクションの作成
- create table collection1(...);
mongoDBの時は、コレクションに対して列を規定する必要がない(データごとに構造は異なるので)
db.createCollection("collection1")
コレクション名のリネーム
- rename table test1 to test1_backup
db.test1.renameCollection('test1_backup')
コレクションにドキュメントを登録
- insert into collection1 (id,name) values(1, 'alice');
db.collection1.insert({
id: 1,
name : "alice",
})
## select: コレクションを検索
- select * from collection1;
```language-js
db.collection1.find({})
- select * from collection1 where id = 1
検索条件をfind()の第二引数に指定する
db.collection1.find({}, {id:1})
- select count(*) from collection1;
db.collection1.count();
- select * from collection1 limit 1;
db.collection1.find().limit(1);
- select * from collection1 where site_url = "www.yahoo.co.jp"
db.collection1.find( { site_url: "www.yahoo.co.jp" } )
- select * from collection1 where site_url REGEXP( "www.yahoo.co.jp$")
db.collection1.find( { site_url: { $regex: 'yahoo\.co\.jp$' } } )
- select * from collection1 order by id asc;
db.collection1.find({}).sort({id:1})
- select * from collection1 order by id desc;
db.collection1.find({}).sort({id:-1})
- select category_id, count(*) from collection1 group by category_id;
db.collection1.aggregate([{
$group: { "_id": "$category_id", "count": { "$sum": 1 } }
}]);
cliで[Type "it" for more]のメッセージが出るのを防ぐ
mongoのcliでは通常では最初の50件のみ表示され、it
をタイプすることで、続きを見ることができる。
下記のように指定すると10万件づつでページングされるので、大量データを一気に見たいときは指定する
DBQuery.shellBatchSize = 100000
db.collection1.find({}, {id:1})```
### 出力の表示形式を変える
```language-js
db.collection1.find({}, {id:1}).toArray()
構造定義をdescする
MongoDBにはdescが存在しない(レコードによって列定義は異なるので)
delete: コレクションに含まれるdocument(MySQLでの行)を削除
全件削除
- delete from collection1;
db.collection1.remove({});
### 条件を指定して削除
データ型に注意
- delete from collection1 where id = 1;
```language-js
db.collection1.remove({ id: 1 });
delete from collection1 where id = '1';
db.collection1.remove({ id: '1' });
こちらもおススメ