LoginSignup
17
16

More than 5 years have passed since last update.

Mongo DB操作をcommand lineから行う

Last updated at Posted at 2015-07-06

初めに

Mongo DBを操作する一番てっとり早い方法は、Mongo shell (cli)を操作する方法です。
show dbs use xxx(dbの名前) show collectionsなどです。

#mongo
MongoDB shell version: 2.6.0
connecting to: test

> show dbs
admin     (empty)
local     0.078GB
hoge_db   0.078GB

> use hoge_db
switched to db local

> show collections
fuga_col
system.indexes

この作業をBat化したい! という時に、mongo localhost:27017/hoge_db mongobat.jsみたいに、jsファイルの中に処理内容をjavascriptで書くと、javascriptの内容をMongo cliが解釈してBat処理してくれるのですが、このjavascriptに関して自分にずばり参考になる取っ掛かりのSample Codeがうまく見つからなかったので、ご参考までにCodeをチラシの裏しておきます。

以下のような環境/手順を想定しています。

  • Mongoがlocalhost:27017で動いている
  • hoge_dbというDatabaseの下に、fuga_colというCollectionがある
  • 各例にあるようなmongobat.jsを作り、mongo localhost:27017/hoge_db mongobat.jsと実行する

Case#1 CollectionのRecordを全部消す

mongobat.js
print ("Record num for fuga_col: " + db.fuga_col.count());
db.fuga_col.remove({})
print ("Record num for fuga_col: " + db.fuga_col.count());

Case#2 Collectionを一旦削除して、再度作る

mongobat.js
db.fuga_col.drop();
db.createCollection("fuga_col");
print ("Record num for fuga_col: " + db.fuga_col.count());

Case#3 Recordの中身を1つ出力する

mongobat.js
print (JSON.stringify(db.fuga_col.findOne(), null, "  "));

Case#4 Query条件に当てはまるRecordの要素を出力する

ここでは、typeuser_countというfieldがRecordに存在するという想定

mongobat.js
var query = {type:"new_user"};
db.fuga_col.find(query).forEach(function(x){ print(x.user_count); });
17
16
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
17
16