前人未踏の領域へ 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
> 

以下順次更新

GoからMongodbに接続

MongoDBにGo言語でアクセスする。

Go向けの公式Driverは提供されておらず、mgoを使うよう案内される。

labix.org

インストール

go get gopkg.in/mgo.v2

Import

import (
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

接続

Dial関数にURLを渡して接続する。他にDialWithTimeoutというタイムアウト付きのものがある。

session, err := mgo.Dial("192.168.33.13:27017")
if err != nil {
        panic(err)
}
defer session.Close() //遅延実行。先に書いておく

Collectionを取得

mymovieというdbにfilmsというコレクションがあったとする。

type Film struct {
    Title string `json:"title"`
}

//コレクションを検索して値をセット
c := session.DB("mymovie").C("films")
result := Film{}
err = c.Find(bson.M{"title": "Rocky"}).One(&result) //titleがRockeyのものを1件取得してresultに格納

//jsonにして標準出力
text, err := json.Marshal(result)
fmt.Println(string(text))

コード

サンプル様にそれっぽく書き直してるので動かなかったら申し訳ない。

package main

import (
    "encoding/json"
    "fmt"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type Film struct {
    Title string `json:"title"`
}

func main() {
    PrintItems()
}

func PrintItems() {
    session, err := mgo.Dial("192.168.33.13:27017")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    c := session.DB("mymovie").C("films")
    result := Item{}
    err = c.Find(bson.M{"title": "Rocky"}).One(&result)

    text, err := json.Marshal(result)
    fmt.Println(string(text))
}

参考

Ubuntuに最新版Redisをインストールする

Vagrant上に構築したUbuntu 14.04にRedisをソースからコンパイル,インストールする

ダウンロード、解凍

$ sudo apt-get update
$ sudo apt-get install gcc python-dev tcl
$ wget http://download.redis.io/releases/redis-3.0.4.tar.gz
$ tar zxvf redis-3.0.4.tar.gz

コンパイル、インストール

Virtualboxの割り当てメモリが少ないとmake testがこけるので注意

$ cd redis-3.0.4
$ make
$ make test
\o/ All tests passed without errors!

起動

$ src/redis-server
11589:C 13 Sep 08:34:15.898 # Warning: no config file specified, using the default config. In order to specify a config file use src/redis-server /path/to/redis.conf
11589:M 13 Sep 08:34:15.899 # You requested maxclients of 10000 requiring at least 10032 max file descriptors.
11589:M 13 Sep 08:34:15.899 # Redis can't set maximum open files to 10032 because of OS error: Operation not permitted.
11589:M 13 Sep 08:34:15.899 # Current maximum open files is 4096. maxclients has been reduced to 4064 to compensate for low ulimit. If you need higher maxclients increase 'ulimit -n'.
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 3.0.4 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 11589
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

11589:M 13 Sep 08:34:15.901 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
11589:M 13 Sep 08:34:15.902 # Server started, Redis version 3.0.4
11589:M 13 Sep 08:34:15.902 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
11589:M 13 Sep 08:34:15.902 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
11589:M 13 Sep 08:34:15.902 * The server is now ready to accept connections on port 6379

接続

$ src/redis-cli
127.0.0.1:6379> set foo bar
OK
127.0.0.1:6379> get foo
"bar"
127.0.0.1:6379> 

続き

Webチュートリアルがあるのでそれをやってみると良さそう。 Try Redis

参考

http://redis.io/download#installation

www.amazon.co.jp

UbuntuにMongoDBをインストール

しばらくすると忘れるのでメモ。

Install

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org

Start

sudo service mongod start

Stop

sudo service mongod stop

Restart

sudo service mongod restart

参考

docs.mongodb.org

Snappy Ubuntuを試す

Snappy Ubuntu Coreがリリースされたので、Vagrant上で起動してみる。それだけの記事。

Boxを探す

Ubuntu Snappyのイメージを探す。オフィシャルなものが2つほど見つかる。 ubuntu-15.04-snappy-core-stableというのが安定版のようなのでそちらを使うことにする。

Discover Vagrant Boxes | Atlas by HashiCorp

インストール、起動

$ cd [任意のディレクトリ]
$ vagrant init ubuntu/ubuntu-15.04-snappy-core-stable
...output 省略
$ vagrant up
...output 省略

これで起動した。

確認

SSHで接続してみる。

$ vagrant ssh
Welcome to Ubuntu 15.04 (GNU/Linux 3.19.0-15-generic x86_64)

 * Documentation:  https://help.ubuntu.com/
Welcome to snappy Ubuntu Core, a transactionally updated Ubuntu.

 * See https://ubuntu.com/snappy

It's a brave new world here in snappy Ubuntu Core! This machine
does not use apt-get or deb packages. Please see 'snappy --help'
for app installation and transactional updates.

apt-get はもう使わないんだぜとかいてある。 snappy --help 見ろというので確認してみることにしよう。

snappyコマンド

snappy コマンドを使って色々とやるらしい。

$ which snappy
/usr/bin/snappy
$ snappy --help
Usage:
  snappy [OPTIONS] <command>

Help Options:
  -h, --help  Show this help message

Available commands:
  booted              Flag that rootfs booted successfully
  build               Builds a snap package (aliases: bu)
  config              Set configuraion for a installed package.
  firstboot           internal
  hw-assign           Assign a hardware device to a package
  hw-info             List assigned hardware device for a package
  hw-unassign         Unassign a hardware device to a package
  info                Display a summary of key attributes of the snappy system.
  install             Install a snap package
  internal-run-hooks  internal
  internal-unpack     internal
  list                List active components installed on a snappy system (aliases: li)
  login               Log into the store
  purge               Remove all the data from the listed packages
  remove              Remove a snapp part
  rollback            Rollback to a previous version of a package
  search              Search for packages to install (aliases: se)
  set                 Set properties of system or package
  update              Update all installed parts
  versions            (deprecated) please use "list"

各コマンドのヘルプは snappy [command] --help で確認できる。

$ snappy list --help
Usage:
  snappy [OPTIONS] list [list-OPTIONS]

Provides a list of all active components installed on a snappy system

If requested, the command will find out if there are updates for any of the
components and indicate that by appending a * to the date. This will be slower as it requires a round trip to the app store on the network.

The
developer information refers to non-mainline versions of a package (much like PPAs in deb-based Ubuntu). If the package is the primary version of that
package in Ubuntu then the developer info is not shown. This allows one to identify packages which have custom, non-standard versions installed. As a
special case, the “sideload” developer refers to packages installed manually on the system.

When a verbose listing is requested, information
about the channel used is displayed; which is one of alpha, beta, rc or stable, and all fields are fully expanded too. In some cases, older (inactive)
versions of snappy packages will be installed, these will be shown in the verbose output and the active version indicated with a * appended to the
name of the component.

Help Options:
  -h, --help         Show this help message

[list command options]
      -u, --updates  Show available updates (requires network)
      -v, --verbose  Show channel information and expand all fields

snappy search

ストアか利用可能なパッケージを探すコマンド。

$ snappy search --help
Usage:
  snappy [OPTIONS] search [search-OPTIONS]

Query the store for available packages

Help Options:
  -h, --help          Show this help message
[search command options]
          --show-all  Show all available forks of a package

--show-all で全て表示してくれるっぽいので実行してみる。

$ snappy search --show-all
Name                     Version   Summary                        
crossbar.crossbar        0.10.4    Crossbar.io                    
gumstix-overo.ash        0.1       gumstix-overo                  
webcam-demo              1.0.1     webcam-demo                    
pi2.lool                 0.11      pi2                            
go-example-webserver     1.0.6     go-example-webserver           
config-example           1.0.5     config-example                 
pastebinit.mvo           1.4.0.0.2 pastebinit                     
hello-dbus-fwk.canonical 1.0.0     hello-dbus-fwk                 
docker                   1.6.0.003 Docker                         
8nzc1x4iim2xj1g2ul64     43        Returns for store credit only. 
system-status.victor     1.0.3     System status web portal       
webdm                    0.5       webdm                          
beagleblack              1.7       beagleblack                    
hello-world              1.0.14    hello-world                    
hello-world.jdstrand     1.5.1     hello-world                    
generic-amd64            1.1       generic-amd64                  
xkcd-webserver           0.4       xkcd-webserver              

dockerがいるな。Docker Imageで使用するためにSnappyを使おうと思っていたけどSnappy自身もDockerのホストとして使えるのか。 他には hello-worldgo-example-webserver あたりが気になったので入れてみる。

$ sudo snappy install docker
sudo: unable to resolve host ubuntu-core-stable-2
Installing docker
Starting download of docker
8.36 MB / 8.36 MB [==============================================================================================================] 100.00 % 79.07 KB/s 
Done
Name          Date       Version   Developer 
ubuntu-core   2015-04-23 2         ubuntu    
docker        2015-05-02 1.6.0.003           
generic-amd64 2015-04-23 1.1                 

sudoコマンドを使うとhost名解決ができないといって怒られるがインストールはできる。 上記3点を入れた後の状態。

$ snappy list
Name                 Date       Version   Developer 
ubuntu-core          2015-04-23 2         ubuntu    
docker               2015-05-02 1.6.0.003           
go-example-webserver 2015-05-02 1.0.6     canonical 
hello-world          2015-05-02 1.0.14    canonical 
generic-amd64        2015-04-23 1.1

とりあえずdocker入れたのであとはどうとでもなりそうだけど、 Snappy自体がなんのこっちゃか分かってないので続きはまた今度。

Docker Imageの履歴を確認する

docker inspect コマンドを使うことでImageの状態を知ることができるが、 docker historyコマンドを使うとImageに対してそれまでに加えてきた内容を知ることができる。

例としてOfficialのtomcatをダウンロードしてみる。 docker history コマンドはImageがローカルにダウンロード済みである必要がある。

$ docker pull tomcat:latest
$ docker history tomcat
IMAGE               CREATED             CREATED BY                                      SIZE
cef95d42a67e        6 days ago          /bin/sh -c #(nop) CMD [catalina.sh run]         0 B
2f84c3ab2483        6 days ago          /bin/sh -c #(nop) EXPOSE map[8080/tcp:{}]       0 B
be11664c34d5        6 days ago          /bin/sh -c set -x                               && curl -fSL "$TOMCAT_TGZ_   13.09 MB
df8dde32ea2f        2 weeks ago         /bin/sh -c #(nop) ENV TOMCAT_TGZ_URL=https://   0 B
2c367253b67d        2 weeks ago         /bin/sh -c #(nop) ENV TOMCAT_VERSION=8.0.21     0 B
5e5452f6e864        3 weeks ago         /bin/sh -c #(nop) ENV TOMCAT_MAJOR=8            0 B
e00f3a75a41b        3 weeks ago         /bin/sh -c gpg --keyserver pool.sks-keyserver   109.4 kB
8b95d6fd0d61        3 weeks ago         /bin/sh -c #(nop) WORKDIR /usr/local/tomcat     0 B
5d06ddb41dfc        3 weeks ago         /bin/sh -c mkdir -p "$CATALINA_HOME"            0 B
23d0b073332c        3 weeks ago         /bin/sh -c #(nop) ENV PATH=/usr/local/tomcat/   0 B
2a6c03336c25        3 weeks ago         /bin/sh -c #(nop) ENV CATALINA_HOME=/usr/loca   0 B
7f628ae52eec        3 weeks ago         /bin/sh -c apt-get update && apt-get install    164.5 MB
7428e160408e        3 weeks ago         /bin/sh -c #(nop) ENV JAVA_DEBIAN_VERSION=7u7   0 B
22df52eafda5        3 weeks ago         /bin/sh -c #(nop) ENV JAVA_VERSION=7u75         0 B
4d0d7acdf9db        3 weeks ago         /bin/sh -c apt-get update && apt-get install    676.1 kB
b7820d1ee4ee        3 weeks ago         /bin/sh -c apt-get update && apt-get install    44.34 MB
65688f7c61c4        3 weeks ago         /bin/sh -c #(nop) CMD [/bin/bash]               0 B
d338bb63f151        3 weeks ago         /bin/sh -c #(nop) ADD file:f9472dcedb28e889f7   122.8 MB
511136ea3c5a        22 months ago                                                       0 B

コマンドが長い場合は省略されてしまうので、その場合は --no-trunc オプションをつけることでコマンドを省略なしで表示できる。

$ docker history --no-trunc tomcat:8.0
IMAGE                                                              CREATED             CREATED BY                                                                                                                     SIZE
cef95d42a67e5abbc7d9d6b3622e89b1ee74c119253dbb4af1f284de105c39f3   6 days ago          /bin/sh -c #(nop) CMD [catalina.sh run]                                                                                        0 B
2f84c3ab24836342a40c92a64ecf89dccea1c239bcba680d114b7d06ea7df8b5   6 days ago          /bin/sh -c #(nop) EXPOSE map[8080/tcp:{}]                                                                                      0 B
be11664c34d591a675d1385ea58021c9d15b5ac0eb27303ba52b5c21d003d2b7   6 days ago          /bin/sh -c set -x                                                                                                              && curl -fSL "$TOMCAT_TGZ_URL" -o tomcat.tar.gz    && curl -fSL "$TOMCAT_TGZ_URL.asc" -o tomcat.tar.gz.asc    && gpg --verify tomcat.tar.gz.asc    && tar -xvf tomcat.tar.gz --strip-components=1    && rm bin/*.bat     && rm tomcat.tar.gz*   13.09 MB
df8dde32ea2f80831fb10c5131e29248b7a1d7ffaa2d48b6d7674f4518f4ea3a   2 weeks ago         /bin/sh -c #(nop) ENV TOMCAT_TGZ_URL=https://www.apache.org/dist/tomcat/tomcat-8/v8.0.21/bin/apache-tomcat-8.0.21.tar.gz       0 B
2c367253b67d0ef468d6f73ef28afa67c6de6e639cf8b8450685334a0c9261ff   2 weeks ago         /bin/sh -c #(nop) ENV TOMCAT_VERSION=8.0.21                                                                                    0 B
5e5452f6e864a3e28ce424ba7fd7d62e35a5a5a9240e1c489f3e6c41df5abf5a   3 weeks ago         /bin/sh -c #(nop) ENV TOMCAT_MAJOR=8                                                                                           0 B
e00f3a75a41b17a6c5b0ad9d0b179442abb03bdaedf96f3e335d5265602b1188   3 weeks ago         /bin/sh -c gpg --keyserver pool.sks-keyservers.net --recv-keys                                                                 05AB33110949707C93A279E3D3EFE6B686867BA6    07E48665A34DCAFAE522E5E6266191C37C037D42    47309207D818FFD8DCD3F83F1931D684307A10A5    541FBE7D8F78B25E055DDEE13C370389288584E7    61B832AC2F1C5A90F0F9B00A1C506407564C17A3    79F7026C690BAA50B92CD8B66A3AD3F4F22C4FED    9BA44C2621385CB966EBA586F72C284D731FABEE    A27677289986DB50844682F8ACB77FC2E86E29AC    A9C5DF4D22E99998D9875A5110C01C5A2F6059E7    DCFD35E0BF8CA7344752DE8B6FB21E8933C60243    F3A04C595DB5B6A5F1ECA43E3B7BBB100D811BBE    F7DA48BB64BCB84ECBA7EE6935CD23C10D498E23   109.4 kB
8b95d6fd0d61c61b9ad7cc87d8be1e43da58a83d4379ab5d818385e87c68d56b   3 weeks ago         /bin/sh -c #(nop) WORKDIR /usr/local/tomcat                                                                                    0 B
5d06ddb41dfc068e783871f409d28eaca741043953780c55fc03b199f9fb1504   3 weeks ago         /bin/sh -c mkdir -p "$CATALINA_HOME"                                                                                           0 B
23d0b073332ce84e6015cd5884d4ddf7c178c2902145edaad1d938dfa502d85e   3 weeks ago         /bin/sh -c #(nop) ENV PATH=/usr/local/tomcat/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin                  0 B
2a6c03336c25d7e548798577be2fcd322cd4599ff949bc78d1d42c8f7f1afc59   3 weeks ago         /bin/sh -c #(nop) ENV CATALINA_HOME=/usr/local/tomcat                                                                          0 B
7f628ae52eec9df9891177702bbd3c44b8442a5f087c69d660b21b688f1bc5fb   3 weeks ago         /bin/sh -c apt-get update && apt-get install -y openjdk-7-jre-headless="$JAVA_DEBIAN_VERSION" && rm -rf /var/lib/apt/lists/*   164.5 MB
7428e160408efe1e37d0710fba2a1777f7beab5411014eabde3a31c9980d3288   3 weeks ago         /bin/sh -c #(nop) ENV JAVA_DEBIAN_VERSION=7u75-2.5.4-2                                                                         0 B
22df52eafda5575c11112c744cda32d60c2ac9b70f97def69ad9f1355cb5d40b   3 weeks ago         /bin/sh -c #(nop) ENV JAVA_VERSION=7u75                                                                                        0 B
4d0d7acdf9dbc175ba89f5a32b08c78a7659ba988c276a92f39dc83d69818e69   3 weeks ago         /bin/sh -c apt-get update && apt-get install -y unzip && rm -rf /var/lib/apt/lists/*                                           676.1 kB
b7820d1ee4ee3aaad7d45bde22f0e2c79e97097384cd4321284a39c04bb4a1f4   3 weeks ago         /bin/sh -c apt-get update && apt-get install -y --no-install-recommends                                                                            ca-certificates                         curl                                    wget                && rm -rf /var/lib/apt/lists/*   44.34 MB
65688f7c61c4e8f3cce67714991d5a6d36d6bb3890e439cfcb5450db5ae9d530   3 weeks ago         /bin/sh -c #(nop) CMD [/bin/bash]                                                                                              0 B
d338bb63f1516c639f195833750da8b5b9bbf53a1124a8275088406f3a03724e   3 weeks ago         /bin/sh -c #(nop) ADD file:f9472dcedb28e889f7253817dcd6a0412c51a3fe0dc0fbea98041e426fea6ce0 in /                               122.8 MB
511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158   22 months ago                                                                                                                                      0 B

公式サイトや他のImageでDockerfileが公開されていないケースでも、Historyを見ることで色々と参考にすることができるだろう。

/* Responsive: yes */