1. 程式人生 > >MongDB學習03:資料基本操作

MongDB學習03:資料基本操作

文件 組成 集合;集合 組成 資料庫。
文件 如同python中dict.
資料庫操作是使用JavaScript shell進行操作

資料庫操作

  • 檢視所有資料庫
    show dbs
  • use 切換資料操作,也是建立資料庫命令
    use test
  • 資料庫刪除
    db.dropDatabase()
  • 檢視集合
    show collections顯示所有資料庫中的集合,或者show tables
  • insert 資料建立
    post = {"title":"My Blog Post","content":"Here's my blog post.","date":new Date()}

    db.blog.insert(post)
    1. 批量插入
      batchInsert([{name:Jack,sex:male},{name:Bob,age:25},{name:Rose,age:23},{name:Dan,age:36}])
    2. save(),是一個shell函式,如果如果有相同_id的,直接進行替代操作,而insert則會報錯。
  • find()/findOne() 資料讀取
    db.blog.find()
    db.test_collection.find().count() //檢視資料條數
    db.test_collection.find().skip(3).limit(2).sort({x:1})//跳過前三條,限制條數為2,並以x排序


    高階功能:
    1.只返回需要的鍵值:
    db.users.find({},{"username" : 1,"email" : 1})
    但“_id”預設都要返回,此時用:
    db.users.find({},{"username" : 1,"_id" : 0})
    2.查詢條件:$lt,$lte,$gt,$gte對應<,<=,>,>=
    可用於數和日期。
    db.users.find({"age":{"$lt":30,"$gt":20}})
    3.元操作符$and,$or,$nor
    db.users.find({"$and":[{"x":{"$lt":1}},{"x":4}]})

  • update() 資料更新

1.至少接受兩個引數(一個限定條件,一個新文件)
post.comments = [] //改值
db.blog.update({title:"My Blog Post"},post) //更新
db.blog.update({title:"My Blog Post"},{$set:{"content":"U R my boby!"}}) //用$set{}進行部分更新
2.upsert 即update的第三個引數值為true,update({},{},true)
db.blog.update({title:"My Blog Week"},{title:"My Blog Week","content":"My weekday very happy!"},true) //實現update insert操作,不存在的資料自動插入
update 預設只更改查詢到的第一條資訊,更新查到的所有資料用:
>update({x:1},{$set:{x:2}},false,true)
db.blog.find() //檢視
想檢視更新了多少資料量用命令:
>db.runCommand({getLastError:1})
{
    "err":null,
    "updatedExisting":true,
    "n":5,
    "ok":true
}//其中n表示更新文件數

3.返回被更新的文件(findAndModify):
>db.runCommand({"findAndModify":"processes","query":{"status":"READY"},"sort":{"priority":-1},"update":{"$set":{"status":"RUNNING"}})
//但 返回的是更新前的文件。
findAndModify還有很多可以用的欄位:
findAndModify=》字串,集合名;
query=》查詢文件,檢索文件的條件;
sort=》排序結果條件;
update/remove=》修改器文件(和remove必定指定一個);
new=》布林型別,表示返回更新前還是更新後的文件,預設是返回更新前的文件;
fields=》文件中需要返回的欄位(可選);
upsert=》



>
  • remove() 資料刪除
    在沒有條件限定時,會將集合中的所有資料全部永久刪除
    db.blog.remove({title:"My Blog Post"})
    (資料庫集合清空:db.collection.drop()和刪除一個文件的時間差不多)

資料修改器

  • $set / $unset在update語句中更新(新增)/刪除部分內容
    修改內嵌文件:
    db.blog.posts.update({"author.name":"joe"},{"$set":{"author.name":"joe scheme"}})
  • $inc用來增加減少某一整型/長整型/雙精度欄位
    db.games.update({"game":"pinball","user":"joe"},{"$inc":{"score":50}})
  • $push / $pop陣列元素中增添/刪除元素
    1. db.blog.posts.update({"title":"A blog Post"},{"$push":{"comments":{"name":"joe","email":"[email protected]","content":"nice post"}}})在陣列末尾加入一個元素,沒有陣列自動新建陣列。
    2. 同時加入多個元素可以用$each輔助:
      db.stock.ticker.update({"_id":"good"},{"$push":{"hourly":{"$each":[25,454,674,66,48]}}})
    3. 固定陣列長度$slice
      db.movies.update({"genre":"horror"},{"$push":{"top10":{"$each":["Nightmare","saw"],"slice":-10}}})會儲存最後10個元素
      如果保留評分最高的10個,這裡可以用到$sort:
      db.movies.update({"genre":"horror"},{"$push":{"top10":{"$each":[{"name":"Nightmare","rating":6.7},{"name":"saw","rating":5.9}],"slice":-10,"$sort":{"rating":-1}}}})
  • $ne / $addToSet 將陣列當成資料集(不重複資料)
    1. db.papers.update({"authors cited":{"$ne":"Richie"}},{"$push":{"authors cited":"Richie}})
    2. db.users.update({"_id":"good01"},{"$addToSet":{"email":{"$each":["[email protected]","[email protected]"]}}})
  • $pop從資料頭/尾刪除元素{"$pop":-1/1}
    $pull刪除匹配的所有元素`
  • $定位操作號進行陣列資料修改
>db.blog.posts.findOne()
{
    "_id":post_id,
    "content":"..,.,..,",
    "comments":[
        {"comment":"good post",
         "author":"John",
         "votes":0
        },
        {"comment":"i thought it was too long",
         "author":"Claire",
         "votes":3
        },
        {"comment":"free coffe",
         "author":"Dan",
         "votes":9
        }
    ]
 }
 // 1.用資料下標
>db.blog.update({"post":post_id},{"$inc":{"comments.0.votes":1}})
//使用$定位符
>db.blog.update({"comments.author":"John"},{"$set":{"comments.$.author":"Jim"}})
//定位符只更新第一個匹配的元素。

修改器速度:
"$inc"不改變文件大小,速度很快;
"$set/$push/insert"會修改集合的填充因子,速度很慢

寫入安全機制

  • 應答式寫入
  • 非應答式寫入