MongoDB入門

データベースMongoDB

MongoDBとは?

 状態:学習中  閲覧数:1,069  投稿日:2014-09-25  更新日:2014-09-29
ドキュメント指向データベース
・NoSQL/スキーマレス(予めデータ形式を決定しておかなくても自由に操作可能)

特徴
・JavaScriptオブジェクト形式でデータを格納

$ sudo service mongod status
mongod (pid 1644) を実行中...


$ mongo --version
MongoDB shell version: 2.4.9



環境


▼/var/www/lib/mongodb/









MongoDB入門

用語

 閲覧数:302 投稿日:2014-09-26 更新日:2014-09-27 
データベース

コレクション
・リレーショナルDBテーブルに該当

ドキュメント
・リレーショナルDBレコードに該当
・格納するデータ形式を予め決めておく必要がない
・異なるデータが来ても、データ構造を変更する必要がない

仕様
・データベースの中にコレクションを作成した時点で、データベースが作成される
※コレクションがない状態のデータベースは存在しない

コマンド

 閲覧数:322 投稿日:2014-09-27 更新日:2014-09-28 

DataBase


一覧
show dbs;

新規作成 or データベース切替
use データベース名;

削除
db.dropDatabase();


実例


起動
# mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb

> help
        db.help()                    help on db methods
       db.mycoll.help()             help on collection methods
       sh.help()                    sharding helpers
       rs.help()                    replica set helpers
       help admin                   administrative help
       help connect                 connecting to a db help
       help keys                    key shortcuts
       help misc                    misc things to know
       help mr                      mapreduce

       show dbs                     show database names
       show collections             show collections in current database
       show users                   show users in current database
       show profile                 show most recent system.profile entries with time >= 1ms
       show logs                    show the accessible logger names
       show log [name]              prints out the last segment of log in memory, 'global' is default
       use <db_name>                set current database
       db.foo.find()                list objects in collection foo
       db.foo.find( { a : 1 } )     list objects in foo where a == 1
       it                           result of the last line evaluated; use to further iterate
       DBQuery.shellBatchSize = x   set default number of items to display on shell
       exit                         quit the mongo shell

> exit

データベース一覧
> show dbs;
・コレクションを作成していないのでmydb2表示されない
・local … システムが最初に作成するデータベース
local   0.078125GB


> db.createCollection('test');
{ "ok" : 1 }

> show dbs;
local   0.078125GB
mydb    0.203125GB


データベース切替
> use local
switched to db local

> use mydb2
switched to db mydb2


> show dbs;
・コレクションを作成していないのでmydb2は表示されない
local   0.078125GB
mydb    0.203125GB


> use mydb;
switched to db mydb

> db.dropDatabase();
{ "dropped" : "mydb", "ok" : 1 }

> show dbs;
local   0.078125GB


Collection

 閲覧数:284 投稿日:2014-09-28 更新日:2014-09-28 

用語


新規作成
・db.createCollection('col');

一覧
・show collections;

名前変更
・db.col.renameCollection('newCol');

削除
・db.col.drop();


実例


# mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb

> show dbs;
local   0.078125GB

> use mydb;
switched to db mydb

> db.createCollection('users');
{ "ok" : 1 }

> show collections;
system.indexes
users

・system.indexesは自動生成されるコレクション

> db.users.renameCollection('persons');
{ "ok" : 1 }


> show collections;
persons
system.indexes


> db.persons.drop();
true


> show collections;
system.indexes


ドキュメント

 閲覧数:429 投稿日:2014-09-29 更新日:2014-09-29 

用語


新規作成
・db.コレクション名.insert();

全抽出
・db.コレクション名.find();

全削除
・db.コレクション名.remove();

個数を確認
・db.コレクション名.count();


実例


$ mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user


> show dbs;
・adminはシステムが自動作成したデータベース
admin   (empty)
local 0.078125GB
mydb 0.203125GB


> use mydb;
switched to db mydb


> show collections;
system.indexes


> db.createCollection('users');
{ "ok" : 1 }


> db.users.insert({name:"taguchi",score:30});
> db.users.insert({name:"fkoji",tags:["web","mobile"]});
> db.users.find();
{ "_id" : ObjectId("542951e896cf09d6b9785eeb"), "name" : "taguchi", "score" : 30 }
{ "_id" : ObjectId("5429522b96cf09d6b9785eec"), "name" : "fkoji", "tags" : [ "web", "mobile" ] }


> db.users.count();
2


> db.users.remove();
> db.users.find();


データ挿入 / db.テーブル名.insert

 閲覧数:290 投稿日:2014-09-30 更新日:2014-09-30 
$  mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb


>for(var i =0; i<4; i++){
db.users.insert({
name:"user-"+i,
team:"team-"+(i%3),//3で割った余り。すなわち0か1か2
score:Math.floor(Math.random()*100) //適当な乱数
});
}
... db.users.insert({
... name:"user-"+i,
... team:"team-"+(i%3),//3で割った余り。すなわち0か1か2
... score:Math.floor(Math.random()*100) //適当な乱数
... });
... }


> db.users.find();
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }


>for(var i =4; i<6; i++){
db.users.insert({
name:"user-"+i,
team:"team-"+(i%3)//3で割った余り。すなわち0か1か2
});
}

> db.users.find();
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "_id" : ObjectId("542a1a44d2bb2ea385265093"), "name" : "user-4", "team" : "team-1" }
{ "_id" : ObjectId("542a1a44d2bb2ea385265094"), "name" : "user-5", "team" : "team-2" }


条件付きでデータを抽出

 閲覧数:333 投稿日:2014-10-01 更新日:2014-10-01 

条件付きfind


$  mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb


全検索
> db.users.find();
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "_id" : ObjectId("542a1a44d2bb2ea385265093"), "name" : "user-4", "team" : "team-1" }
{ "_id" : ObjectId("542a1a44d2bb2ea385265094"), "name" : "user-5", "team" : "team-2" }


空のオブジェクトを渡す
・上記と同じ意味
db.users.find({});
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "_id" : ObjectId("542a1a44d2bb2ea385265093"), "name" : "user-4", "team" : "team-1" }
{ "_id" : ObjectId("542a1a44d2bb2ea385265094"), "name" : "user-5", "team" : "team-2" }


nameが"user-1"を抽出
> db.users.find({name:"user-1"});
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "name" : "user-1", "team" : "team-1", "score" : 27 }


正規表現
・nameが"user-1"~"user-3"を抽出
> db.users.find({name:/user-[1-3]/});
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }


scoreが30より大きいものを抽出
・$gtは、より大きいを意味する演算子
・greater thanの略
> db.users.find({score:{$gt:30}});
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2", "team" : "team-2", "score" : 86 }


scoreが86以上を抽出
・$gteは、以上を意味する演算子
・greater than equalの略
db.users.find({score:{$gte:86}});
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2", "team" : "team-2", "score" : 86 }


scoreが22以下を抽出
・$lteは、以下を意味する演算子
・less than equalの略
> db.users.find({score:{$lte:22}});
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }


scoreが22未満を抽出
・$ltは、未満を意味する演算子
・less thanの略
> db.users.find({score:{$lt:22}});

nameが"user-1"ではないものを抽出
・$neは、not equalを意味する演算子
> db.users.find({name:{$ne:"user-1"}});
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "_id" : ObjectId("542a1a44d2bb2ea385265093"), "name" : "user-4", "team" : "team-1" }
{ "_id" : ObjectId("542a1a44d2bb2ea385265094"), "name" : "user-5", "team" : "team-2" }


and、or、distinct … 重複なく値を取得

 閲覧数:324 投稿日:2014-10-02 更新日:2014-10-02 

起動


$  mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb



一覧


$in
・配列の中にあるかどうか

$exists:true
・存在するか


AND


//AND 2通りの書き方がある
パターン1
・,区切り
・幾つでも書ける
> db.users.find({
... team:"team-0",
... score:{$lt:50}
... });
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }


パターン2
・$and演算子利用
・項目を{}で囲む
> db.users.find({
... $and:[
... {team:"team-0"},
... {score:{$lt:50}}
... ]
... });
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }


「"team-0"か"team-1"」で「scoreがあるもの」を抽出
> db.users.find({
... $and:[
... {team:{$in:["team-0","team-1"]}},
... {score:{$exists:true}}
... ]
... });
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }



OR


「"team-0"か"team-1"」もしくは「scoreがあるもの」を抽出
> db.users.find({
... $or:[
... {team:{$in:["team-0","team-1"]}},
... {score:{$exists:true}}
... ]
... });
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "_id" : ObjectId("542a1a44d2bb2ea385265093"), "name" : "user-4", "team" : "team-1" }



distinct


重複なく値を取得
> db.users.distinct('team');
[ "team-0", "team-1", "team-2" ]


findOne、skip、limit、sort … 抽出結果を加工して表示

 閲覧数:334 投稿日:2014-10-03 更新日:2014-10-03 
全件抽出後、keyがnameを表示
> db.users.find({},{name:1});
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0" }
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "name" : "user-1" }
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2" }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3" }
{ "_id" : ObjectId("542a1a44d2bb2ea385265093"), "name" : "user-4" }
{ "_id" : ObjectId("542a1a44d2bb2ea385265094"), "name" : "user-5" }


全件抽出後、keuがnameを非表示
> db.users.find({},{name:0});
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "team" : "team-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "team" : "team-1", "score" : 27 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "team" : "team-2", "score" : 86 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "team" : "team-0", "score" : 22 }
{ "_id" : ObjectId("542a1a44d2bb2ea385265093"), "team" : "team-1" }
{ "_id" : ObjectId("542a1a44d2bb2ea385265094"), "team" : "team-2" }


全件抽出後、keyがname、scoreを表示
> db.users.find({},{name:1,score:1});
{ "_id" : ObjectId("542a19e9d2bb2ea38526508f"), "name" : "user-0", "score" : 24 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265090"), "name" : "user-1", "score" : 27 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265091"), "name" : "user-2", "score" : 86 }
{ "_id" : ObjectId("542a19e9d2bb2ea385265092"), "name" : "user-3", "score" : 22 }
{ "_id" : ObjectId("542a1a44d2bb2ea385265093"), "name" : "user-4" }
{ "_id" : ObjectId("542a1a44d2bb2ea385265094"), "name" : "user-5" }


全件抽出後、keyがnameを表示、scoreを非表示は×
・例外を覗き、1と0を同時使用不可
> db.users.find({},{name:1,score:0});
error: {
       "$err" : "You cannot currently mix including and excluding fields. Contact us if this is an issue.",
       "code" : 10053
}


例外
・idを非表示する時だけ、1と0を同時使用可能
・全件抽出後、keyがname、scoreを表示。idは非表示
> db.users.find({},{name:1,score:1,_id:0});
{ "name" : "user-0", "score" : 24 }
{ "name" : "user-1", "score" : 27 }
{ "name" : "user-2", "score" : 86 }
{ "name" : "user-3", "score" : 22 }
{ "name" : "user-4" }
{ "name" : "user-5" }



抽出結果件数制限


抽出結果の最初の1件だけ表示
> db.users.findOne({},{_id:0});
{ "name" : "user-0", "team" : "team-0", "score" : 24 }


3件
> db.users.find({},{_id:0}).limit(3);
{ "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "name" : "user-2", "team" : "team-2", "score" : 86 }



最初の2件スキップ後、3件表示
> db.users.find({},{_id:0}).skip(2).limit(3);
{ "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "name" : "user-4", "team" : "team-1" }


scoreが大きい順
> db.users.find({},{_id:0}).sort({score:-1});
{ "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "name" : "user-4", "team" : "team-1" }
{ "name" : "user-5", "team" : "team-2" }


scoreが小さい順
> db.users.find({},{_id:0}).sort({score:1});
{ "name" : "user-4", "team" : "team-1" }
{ "name" : "user-5", "team" : "team-2" }
{ "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "name" : "user-0", "team" : "team-0", "score" : 24 }
{ "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "name" : "user-2", "team" : "team-2", "score" : 86 }


索引 / インデックス

 閲覧数:309 投稿日:2014-10-05 更新日:2014-10-05 
$ cd /var/www/lib/mongodb/
$ mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb


> db.users.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "mydb.users",
"name" : "_id_"
}
]


score昇順インデックス
・1は昇順、-1は降順
> db.users.ensureIndex({score:1});
> db.users.getIndexes()

[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "mydb.users",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"score" : 1
},
"ns" : "mydb.users",
"name" : "score_1"
}
]


インデックス削除
> db.users.dropIndexes({score:1});
{
"nIndexesWas" : 2,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}


> db.users.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "mydb.users",
"name" : "_id_"
}
]


名前に対してユニークなインデックスを設定
> db.users.ensureIndex({name:1},{unique:true});

重複データを挿入しようとするとエラー
> db.users.insert({name:"user-0"});
E11000 duplicate key error index: mydb.users.$name_1  dup key: { : "user-0" }



データを更新する方法 / update

 閲覧数:297 投稿日:2014-10-05 更新日:2014-10-05 
user-0の全てをscore:100へ置きかえる
> db.users.update({name:"user-0"},{score:100});
> db.users.find({},{_id:0});
{ "score" : 100 }
{ "name" : "user-1", "team" : "team-1", "score" : 27 }
{ "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "name" : "user-4", "team" : "team-1" }
{ "name" : "user-5", "team" : "team-2" }


user-1のscoreだけを100へ置きかえる
> db.users.update({name:"user-1"},{$set:{score:100}});
> db.users.find({},{_id:0});
{ "score" : 100 }
{ "name" : "user-1", "team" : "team-1", "score" : 100 }
{ "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "name" : "user-4", "team" : "team-1" }
{ "name" : "user-5", "team" : "team-2" }


削除
・$unsetで空文字指定
> db.users.update({name:"user-1"},{$unset:{score:""}});
> db.users.find({},{_id:0});
{ "score" : 100 }
{ "name" : "user-1", "team" : "team-1" }
{ "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "name" : "user-4", "team" : "team-1" }
{ "name" : "user-5", "team" : "team-2" }


+10
> db.users.update({name:"user-2"},{$inc:{score:10}});
> db.users.find({},{_id:0});
{ "score" : 100 }
{ "name" : "user-1", "team" : "team-1" }
{ "name" : "user-2", "team" : "team-2", "score" : 96 }
{ "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "name" : "user-4", "team" : "team-1" }
{ "name" : "user-5", "team" : "team-2" }


-10
> db.users.update({name:"user-2"},{$inc:{score:-10}});
> db.users.find({},{_id:0});
{ "score" : 100 }
{ "name" : "user-1", "team" : "team-1" }
{ "name" : "user-2", "team" : "team-2", "score" : 86 }
{ "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "name" : "user-4", "team" : "team-1" }
{ "name" : "user-5", "team" : "team-2" }


名前変更
・score を myscore へ変更
> db.users.update({name:"user-2"},{$rename:{score:"myscore"}});
> db.users.find({},{_id:0});
{ "score" : 100 }
{ "name" : "user-1", "team" : "team-1" }
{ "name" : "user-3", "team" : "team-0", "score" : 22 }
{ "name" : "user-4", "team" : "team-1" }
{ "name" : "user-5", "team" : "team-2" }
{ "myscore" : 86, "name" : "user-2", "team" : "team-2" }


複数のデータを同時に更新 / multi

 閲覧数:314 投稿日:2014-10-06 更新日:2014-10-06 
$ cd /var/www/lib/mongodb/
$  mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb

> db.users.drop();
true


> for(var i =0; i<6; i++){
... db.users.insert({
... name:"user-"+i,
... team:"team-"+(i%3),//3で割った余り。すなわち0か1か2
... score:Math.floor(Math.random()*100)
... });
... }

> db.users.find({},{_id:0});
{ "name" : "user-0", "team" : "team-0", "score" : 70 }
{ "name" : "user-1", "team" : "team-1", "score" : 5 }
{ "name" : "user-2", "team" : "team-2", "score" : 48 }
{ "name" : "user-3", "team" : "team-0", "score" : 7 }
{ "name" : "user-4", "team" : "team-1", "score" : 92 }
{ "name" : "user-5", "team" : "team-2", "score" : 63 }


削除後再作成
> db.users.find({},{_id:0});
{ "name" : "user-0", "team" : "team-0", "score" : 75 }
{ "name" : "user-1", "team" : "team-1", "score" : 63 }
{ "name" : "user-2", "team" : "team-2", "score" : 70 }
{ "name" : "user-3", "team" : "team-0", "score" : 58 }
{ "name" : "user-4", "team" : "team-1", "score" : 4 }
{ "name" : "user-5", "team" : "team-2", "score" : 13 }


update対象が単数
> db.users.update({team:"team-0"},{$inc:{score:10}});
> db.users.find({},{_id:0});
{ "name" : "user-0", "team" : "team-0", "score" : 85 }
{ "name" : "user-1", "team" : "team-1", "score" : 63 }
{ "name" : "user-2", "team" : "team-2", "score" : 70 }
{ "name" : "user-3", "team" : "team-0", "score" : 58 }
{ "name" : "user-4", "team" : "team-1", "score" : 4 }
{ "name" : "user-5", "team" : "team-2", "score" : 13 }


update対象が複数
> db.users.update({team:"team-0"},{$inc:{score:10}},{multi:true});
> db.users.find({},{_id:0});
{ "name" : "user-0", "team" : "team-0", "score" : 95 }
{ "name" : "user-1", "team" : "team-1", "score" : 63 }
{ "name" : "user-2", "team" : "team-2", "score" : 70 }
{ "name" : "user-3", "team" : "team-0", "score" : 68 }
{ "name" : "user-4", "team" : "team-1", "score" : 4 }
{ "name" : "user-5", "team" : "team-2", "score" : 13 }


upsert、remove

 閲覧数:307 投稿日:2014-10-07 更新日:2014-10-07 

upsert


update+insert
・データが存在していたら更新、存在していなかった挿入を行うupsert
> db.users.find({},{_id:0});
{ "name" : "user-0", "team" : "team-0", "score" : 0 }
{ "name" : "user-1", "team" : "team-1", "score" : 81 }
{ "name" : "user-2", "team" : "team-2", "score" : 61 }
{ "name" : "user-3", "team" : "team-0", "score" : 50 }
{ "name" : "user-4", "team" : "team-1", "score" : 85 }
{ "name" : "user-5", "team" : "team-2", "score" : 25 }


name "jb" がなければ「name:"jb",team:"dotinstall",score:200」を挿入
・name "jb" があれば「name:"jb",team:"dotinstall",score:200」へ更新
> db.users.update({name:"jb"},{name:"jb",team:"dotinstall",score:200},{upsert:true});
> db.users.find({},{_id:0});
{ "name" : "user-0", "team" : "team-0", "score" : 0 }
{ "name" : "user-1", "team" : "team-1", "score" : 81 }
{ "name" : "user-2", "team" : "team-2", "score" : 61 }
{ "name" : "user-3", "team" : "team-0", "score" : 50 }
{ "name" : "user-4", "team" : "team-1", "score" : 85 }
{ "name" : "user-5", "team" : "team-2", "score" : 25 }
{ "name" : "jb", "team" : "dotinstall", "score" : 200 }


name "jb" があれば、「name:"jb",team:"dotinstall",score:300」へ更新
・name "jb" がなければ、「name:"jb",team:"dotinstall",score:300」を挿入
> db.users.update({name:"jb"},{name:"jb",team:"dotinstall",score:300},{upsert:true});[
> db.users.find({},{_id:0});
{ "name" : "user-0", "team" : "team-0", "score" : 0 }
{ "name" : "user-1", "team" : "team-1", "score" : 81 }
{ "name" : "user-2", "team" : "team-2", "score" : 61 }
{ "name" : "user-3", "team" : "team-0", "score" : 50 }
{ "name" : "user-4", "team" : "team-1", "score" : 85 }
{ "name" : "user-5", "team" : "team-2", "score" : 25 }
{ "name" : "jb", "team" : "dotinstall", "score" : 300 }



remove


> db.users.remove({name:"jb"});
> db.users.find({},{_id:0});
{ "name" : "user-0", "team" : "team-0", "score" : 0 }
{ "name" : "user-1", "team" : "team-1", "score" : 81 }
{ "name" : "user-2", "team" : "team-2", "score" : 61 }
{ "name" : "user-3", "team" : "team-0", "score" : 50 }
{ "name" : "user-4", "team" : "team-1", "score" : 85 }
{ "name" : "user-5", "team" : "team-2", "score" : 25 }


> db.users.remove();
> db.users.find();


、mongorestoreデータのバックアップ、復元を行うためのコマンド

 閲覧数:862 投稿日:2014-10-08 更新日:2014-10-08 

mongodump


$ cd /var/www/lib/mongodb/
$  mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb


> show dbs;
admin   (empty)
local   0.078125GB
mydb    0.203125GB

> exit
bye


バックアップ
・デフォルトでdumpディレクトリ作成
$ mongodump -d mydb
connected to: 127.0.0.1
Wed Oct  8 17:17:55.194 DATABASE: mydb   to     dump/mydb
error: boost::filesystem::create_directory: Permission denied: "dump"


$ sudo -s
# mongodump -d mydb
connected to: 127.0.0.1
Wed Oct  8 17:18:22.199 DATABASE: mydb   to     dump/mydb
Wed Oct  8 17:18:22.200         mydb.system.indexes to dump/mydb/system.indexes.bson
Wed Oct  8 17:18:22.200                  1 objects
Wed Oct  8 17:18:22.200         mydb.users to dump/mydb/users.bson
Wed Oct  8 17:18:22.201                  6 objects
Wed Oct  8 17:18:22.201         Metadata for mydb.users to dump/mydb/users.metadata.json


# ls
dump

# exit
exit


$  mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb


> db.users.find();
{ "_id" : ObjectId("5434f261baaeced6bacc2a8c"), "name" : "user-0", "team" : "team-0", "score" : 87 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a8d"), "name" : "user-1", "team" : "team-1", "score" : 11 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a8e"), "name" : "user-2", "team" : "team-2", "score" : 46 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a8f"), "name" : "user-3", "team" : "team-0", "score" : 5 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a90"), "name" : "user-4", "team" : "team-1", "score" : 99 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a91"), "name" : "user-5", "team" : "team-2", "score" : 43 }


> db.users.remove({team:"team-0"});
> db.users.find();
{ "_id" : ObjectId("5434f261baaeced6bacc2a8d"), "name" : "user-1", "team" : "team-1", "score" : 11 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a8e"), "name" : "user-2", "team" : "team-2", "score" : 46 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a90"), "name" : "user-4", "team" : "team-1", "score" : 99 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a91"), "name" : "user-5", "team" : "team-2", "score" : 43 }

> exit
bye


$ mongodump --help
Export MongoDB data to BSON files.

options:
 --help                                produce help message
 -v [ --verbose ]                      be more verbose (include multiple times
                                       for more verbosity e.g. -vvvvv)
 --version                             print the program's version and exit
 -h [ --host ] arg                     mongo host to connect to ( <set
                                       name>/s1,s2 for sets)
 --port arg                            server port. Can also use --host
                                       hostname:port
 --ipv6                                enable IPv6 support (disabled by
                                       default)
 -u [ --username ] arg                 username
 -p [ --password ] arg                 password
 --authenticationDatabase arg          user source (defaults to dbname)
 --authenticationMechanism arg (=MONGODB-CR)
                                       authentication mechanism
 --dbpath arg                          directly access mongod database files
                                       in the given path, instead of
                                       connecting to a mongod  server - needs
                                       to lock the data directory, so cannot
                                       be used if a mongod is currently
                                       accessing the same path
 --directoryperdb                      each db is in a separate directly
                                       (relevant only if dbpath specified)
 --journal                             enable journaling (relevant only if
                                       dbpath specified)
 -d [ --db ] arg                       database to use
 -c [ --collection ] arg               collection to use (some commands)
 -o [ --out ] arg (=dump)              output directory or "-" for stdout
 -q [ --query ] arg                    json query
 --oplog                               Use oplog for point-in-time
                                       snapshotting
 --repair                              try to recover a crashed database
 --forceTableScan                      force a table scan (do not use
                                       $snapshot)



mongorestore


・リストア

--drop
・既にデータベースに同名のデータベースがある場合、上書きするオプション
$ mongorestore --drop
connected to: 127.0.0.1
Wed Oct  8 17:21:19.136 dump/mydb/users.bson
Wed Oct  8 17:21:19.136         going into namespace [mydb.users]
Wed Oct  8 17:21:19.136          dropping
6 objects found
Wed Oct  8 17:21:19.145         Creating index: { key: { _id: 1 }, ns: "mydb.users", name: "_id_" }


$  mongo mydb
MongoDB shell version: 2.4.9
connecting to: mydb


> db.users.find();
{ "_id" : ObjectId("5434f261baaeced6bacc2a8c"), "name" : "user-0", "team" : "team-0", "score" : 87 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a8d"), "name" : "user-1", "team" : "team-1", "score" : 11 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a8e"), "name" : "user-2", "team" : "team-2", "score" : 46 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a8f"), "name" : "user-3", "team" : "team-0", "score" : 5 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a90"), "name" : "user-4", "team" : "team-1", "score" : 99 }
{ "_id" : ObjectId("5434f261baaeced6bacc2a91"), "name" : "user-5", "team" : "team-2", "score" : 43 }


> db.users.find({},{_id:0});
{ "name" : "user-0", "team" : "team-0", "score" : 87 }
{ "name" : "user-1", "team" : "team-1", "score" : 11 }
{ "name" : "user-2", "team" : "team-2", "score" : 46 }
{ "name" : "user-3", "team" : "team-0", "score" : 5 }
{ "name" : "user-4", "team" : "team-1", "score" : 99 }
{ "name" : "user-5", "team" : "team-2", "score" : 43 }

> exit
bye


$ mongorestore --help
Import BSON files into MongoDB.

usage: mongorestore [options] [directory or filename to restore from]
options:
 --help                                produce help message
 -v [ --verbose ]                      be more verbose (include multiple times
                                       for more verbosity e.g. -vvvvv)
 --version                             print the program's version and exit
 -h [ --host ] arg                     mongo host to connect to ( <set
                                       name>/s1,s2 for sets)
 --port arg                            server port. Can also use --host
                                       hostname:port
 --ipv6                                enable IPv6 support (disabled by
                                       default)
 -u [ --username ] arg                 username
 -p [ --password ] arg                 password
 --authenticationDatabase arg          user source (defaults to dbname)
 --authenticationMechanism arg (=MONGODB-CR)
                                       authentication mechanism
 --dbpath arg                          directly access mongod database files
                                       in the given path, instead of
                                       connecting to a mongod  server - needs
                                       to lock the data directory, so cannot
                                       be used if a mongod is currently
                                       accessing the same path
 --directoryperdb                      each db is in a separate directly
                                       (relevant only if dbpath specified)
 --journal                             enable journaling (relevant only if
                                       dbpath specified)
 -d [ --db ] arg                       database to use
 -c [ --collection ] arg               collection to use (some commands)
 --objcheck                            validate object before inserting
                                       (default)
 --noobjcheck                          don't validate object before inserting
 --filter arg                          filter to apply before inserting
 --drop                                drop each collection before import
 --oplogReplay                         replay oplog for point-in-time restore
 --oplogLimit arg                      include oplog entries before the
                                       provided Timestamp (seconds[:ordinal])
                                       during the oplog replay; the ordinal
                                       value is optional
 --keepIndexVersion                    don't upgrade indexes to newest version
 --noOptionsRestore                    don't restore collection options
 --noIndexRestore                      don't restore indexes
 --w arg (=0)                          minimum number of replicas per write



申込→公開11.MongoDBインストール&設定

MongoDBを理解できない



週間人気ページランキング / 9-14 → 9-20
順位 ページタイトル抜粋 アクセス数
1 PHPのmb_send_mail関数でメール送信できない | メール処理システム 29
2 Nginx設定。エラーログレベル | Nginx(Webサーバ) 21
3 Python 3.5 アンインストール / yum remove | Python(プログラミング言語) 11
4 FFmpeg 2.8.15 を yum インストール | ソフトウェアスイート 10
5 PHP実行ユーザ設定 / CentOS6 / Apache | PHP(プログラミング言語) 9
6 PHP Version 7.1.2 php-mecabエクステンション対応 / PHP 7.0.14 からのアップグレード  | MeCab(形態素解析) 8
6 ソースからビルドしたPython 2.7.3 アンインストール失敗 | Python(プログラミング言語) 8
7 touch コマンド / viコマンド。新規ファイル作成時の違い | Linuxコマンド 7
7 さくらVPS0 7
8 9回目-13.MySQL5.7.21設定 | CentOS 7 2週間無料のお試し期間 9回目(さくらVPS) 6
8 「設定ファイルに、暗号化 (blowfish_secret) 用の非公開パスフレーズの設定を必要とするようになりました。」対応 6
9 PHPファイルでchmodエラー | PHP(プログラミング言語) 5
9 設定 2019/1/22 / 一般ユーザがmailコマンドでメール送信 / 管理者がmailコマンドでメール送信 5
10 Postfix | メール処理システム 4
10 CentOSでcpコマンド動作確認するためには、Control + T ではなく、 -v オプションを使用 | cp(Linuxコマンド) 4
10 499 (Request has been forbidden by antivirus) | HTTP(通信プロトコル) 4
10 tar | Linuxコマンド 4
10 Python 3.6 インストール / make altinstall | Python(プログラミング言語) 4
10 「CentOS6」から「CentOS7」への移行 | CentOS 7 (CentOS) 4
10 echo と cat の違い 4
2021/9/21 1:01 更新