valid,invalid

関心を持てる事柄について

9/2学んだこと / MongoDB@dotinstall

MongoDB

# 索引

# 追加
> db.users.ensureIndex({ score: 1 })
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

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

# 削除
> db.users.dropIndex('score_1')
{ "nIndexesWas" : 2, "ok" : 1 }

# Unique索引
> db.users.ensureIndex({ name: 1 }, { unique: 1 })
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}
# 制約が有効なことを確認
> db.users.insert({ name: 'user-0' })
WriteResult({
   "nInserted" : 0,
   "writeError" : {
       "code" : 11000,
       "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.users.$name_1  dup key: { : \"user-0\" }"
   }
})
# 更新

# 値の更新
> db.users.update({ name: 'user-0' }, { $set: {score: 100} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

# 属性の削除
> db.users.update({ name: 'user-0' }, { $unset: {score: ''} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# インクリメント / デクリメント
> db.users.update({ name: 'user-1' }, { $inc: {score: 10} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 属性名の更新
> db.users.update({ name: 'user-1' }, { $rename: {score: 'myscore'} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# 複数ドキュメントの更新
> db.users.update({team: 'team-0' }, {$inc: {score: 10}}, {multi: true})
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

# upsert
> db.users.update({name:'butcher'}, {name:'butcher', team:'dot', score: 350}, {upsert:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

# remove
> db.users.remove({name:'butcher'})
WriteResult({ "nRemoved" : 1 })
# dump

# データベースを指定してdump取得
$ mongodump -d mydb

# 既存のデータベースをドロップしてリストア
$ mongorestore --drop