LoginSignup
8
0

More than 3 years have passed since last update.

MongoDB便利コマンドメモ

Last updated at Posted at 2019-05-08

概要

よく使うけれど忘れてしまう便利なコマンドのメモ。随時更新中。

ドキュメントの更新

・nameがaのドキュメントのageを20に更新

$ db.collection.update({name:"a"}, {$set: {age:20}})

・nameがaのドキュメントのageを20、genderをXに更新

$ db.collection.update({name:"a"}, {$set: {age:20, gender:'X'}})

コレクション名変更

コレクション「oldname」を「newname」に変更

$ db.oldname.renameCollection("newname");

フィールド名変更

コレクション「collection」のフィールド「oldname」を「newname」に変更

$ db.collection.update({}, {$rename:{oldname : 'newname'}}, {multi:true});

新しいデータ10件を検索

$ db.collection.find().sort({ $natural: -1 }).limit(10)

部分一致・先頭一致・後方一致

$ db.collection.find(name: /a/);
$ db.collection.find(name: /^a/);
$ db.collection.find(name: /a$/);

バックアップ・リストア

・コレクション単位でバックアップ

$ mongodump -d database -c collection -o dump

mongodump — MongoDB Manual

・コレクション単位でリストア

$ mongorestore --drop -d database -c collection collection.bson

--drop をつけると移行対象になっているコレクションを削除してからリストアしてくれる。
mongorestore — MongoDB Manual

各コレクションについて一括で調べる

一括操作したいときに便利
db.getCollectionNames() — MongoDB Manual

・サイズを一括で調べる

$ db.getCollectionNames().forEach(function(n){print(n + "," + db[n].stats().storageSize/1024/1024/1024 + "GB")})

・ドキュメント数を一括で調べる

$ db.getCollectionNames().forEach(function(n){print(n + "," + db[n].count())})

・インデックスを一括で調べる

$ db.getCollectionNames().forEach(function(n){print(n); printjson(db[n].getIndexes())})
8
0
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
8
0