LoginSignup
128
131

More than 5 years have passed since last update.

MongoDBのシェルの操作方法メモ

Last updated at Posted at 2012-12-15

便利ページ

公式

参考になったページ


基本的な操作方法

mongo
show dbs
use dbName
show collections
col = db[collectionName]

help
db.help()
col.help()

以下、Twitter streaming apiのJSONを保存したコレクションの操作例

ドキュメント数を表示

db.collectionName.count()
db[collectionName].count()
  • 英数字以外のコレクション名の場合db[collectionName]でアクセスする必要がある

sort, limit

最新10件を表示

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

findで一致したドキュメントの一部プロパティだけを取得

スクリーン名と本文だけを表示

col.find({}, {_id:false, "user.screen_name":true, text:true }).sort({$natural:-1}).limit(10)
  • 入れ子になったプロパティの直接指定は""で囲う

findしたドキュメントに対してjavascript関数を実行して表示

スクリーン名と本文だけを表示

col.find({}).sort({$natural:-1}).limit(10).forEach( function(a){print(a.user.screen_name, ":",  a.text)} )

特定のプロパティが存在しないドキュメントだけを表示

リツイートではない普通のツイートだけ表示

col.find({retweeted_status:{ $exists: false }}).sort({$natural:-1}).limit(5).forEach( function(a){print(a.user.screen_name, ":", a.text )} )

ある配列プロパティの内容が一定値以下のドキュメントだけを表示

リツイートではなくて、かつ、ハッシュタグが2つ未満のツイートだけ表示

col.find( { retweeted_status:{$exists:false}, $where:"this.entities.hashtags.length < 2"  }).sort({$natural:-1}).limit(20).forEach( function(a){ print(a.user.screen_name, ':' , a.text); } )
  • findの$sizeで指定した個数と一致するものが得られるが範囲指定はできないので、$whereをつかう

mongoコマンドの引数指定による操作方法

mongo localhost:27017/dbName --eval 'db["collectionName"].count()' --quiet

または

echo 'print(db["collectionName"].count());' > somescript.js
mongo --quiet localhost:27017/dbName somescript.js

のように操作できる

クエリ結果のJSONを標準出力させてファイルに保存

echo 'shellPrint(db["collectionName"].find().limit(10)));' > query.js
mongo --quiet localhost:27017/dbName query.js > result.json
  • shellPrint()で標準出力にでてくる

クエリ結果を別のコレクションに保存する

128
131
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
128
131