前人未踏の領域へ WEB・インフラ・プログラミング全般編

フロントエンド、バックエンド、インフラ、言語など、アプリ開発、IOT以外の記録

MongoDBコマンドあれこれ

利用頻度が低くて毎度コマンドを忘れるのでメモ。
カッコが必要だったり必要なかったり間違いがち。

$ mongo
> help

help系

コマンド 説明
db.help() dbのメソッドを表示
db.mycoll.help() コレクションメソッドを表示
sh.help() シャーディングのヘルパーメソッドを表示
rs.help() レプリカセットのヘルパーメソッドを表示
help admin 管理コマンドのヘルプ
help connect db接続に関するヘルプ
help keys ショートカットキー
help misc
help mr map reduce

情報表示系

コマンド 説明
show dbs データベース名を表示
show collections データベース内のコレクションを表示
show users
show profile
show logs
show log

ケーススタディ(やってみる)

ucというDBスキーマがある想定

DB一覧

> show dbs
local  0.078GB
uc     0.078GB

DB切り替え

> use uc
switched to db uc

コレクション一覧

> show collections
item
item_image
item_impression
item_video
rss_article
rss_site
system.indexes
tag
user
user_item
user_ranking
user_relationship

item一覧を取得

登場コマンド find, limit, pretty, count

#整形なし
> db.item.find().limit(1)
{ "_id" : ObjectId("55f6b62f95e39671f4000000"), "id" : 1, "name" : "Xperia(TM) Tablet Z", "catch_copy" : "", "parent_id" : null, "category" : "ガジェット", "tag_name" : [ "Xperia", "Android", "Tablet", "Sony" ], "short_description" : "", "description" : "", "data" : null, "stats" : { "rating" : 0, "user_count" : 0, "page_view" : 0 }, "image" : "/2013/04/16/08/1366060785000_3", "links" : [ { "name" : "official", "url" : null }, { "name" : "amazon", "url" : null } ]} }

#pretty()で整形
> db.item.find().limit(1).pretty()
{
    "_id" : ObjectId("55f6b62f95e39671f4000000"),
    "id" : 1,
    "name" : "Xperia(TM) Tablet Z",
    "catch_copy" : "",
    "parent_id" : null,
    "category" : "ガジェット",
    "tag_name" : [
        "Xperia",
        "Android",
        "Tablet",
        "Sony"
    ],
    "short_description" : "",
    "description" : "",
    "data" : null,
    "stats" : {
        "rating" : 0,
        "user_count" : 0,
        "page_view" : 0
    },
    "image" : "/2013/04/16/08/1366060785000_3",
    "links" : [
        {
            "name" : "official",
            "url" : null
        },
        {
            "name" : "amazon",
            "url" : null
        }
    ]
}

件数取得

# item件数
> db.item.find().count()
1627
# categoryがガジェットなitem
> db.item.find({category:"ガジェット"}).count()
23
# category == ガジェット and tag_name == HHKB
> db.item.find({category:"ガジェット", tag_name:"HHKB"}).count()
1

size とcountの違い

  • count()はfind()結果の総件数
  • size()はskipやlimitを考慮したレスポンス数
> db.tag.find().size()
2496
> db.tag.find().count()
2496
> db.tag.find().skip(1000).size()
1496
> db.tag.find().skip(1000).count()
2496
> db.tag.find().skip(1000).limit(1000).size()
1000
> db.tag.find().skip(1000).limit(1000).count()
2496
> 

以下順次更新

/* Responsive: yes */