1.前言
最近在學習MongoDB,資料修改這一部分的內容較多,命令比較繁瑣,所以將一些常用的修改命令總結在這篇部落格中,方便今後學習的查閱。
2.命令總結
1). insert()
db.collection.insert(x) x就是要更新的對象,只能是單條記錄,如:
db.collection.insert({_id:1,name:"test",count:1})
當需要批量插入的時候,可以在shell中使用for迴圈,如:
for(var i=0;i<16;i++){
db.mytest.insert({_id:i,name:"test"+i,count:i})
}
此時如果用find()命令查詢插入的資料,結果是這樣的:
> db.mytest.find()
{ "_id" : 0, "name" : "test0", "count" : 0 }
{ "_id" : 1, "name" : "test1", "count" : 1 }
{ "_id" : 2, "name" : "test2", "count" : 2 }
{ "_id" : 3, "name" : "test3", "count" : 3 }
{ "_id" : 4, "name" : "test4", "count" : 4 }
{ "_id" : 5, "name" : "test5", "count" : 5 }
{ "_id" : 6, "name" : "test6", "count" : 6 }
{ "_id" : 7, "name" : "test7", "count" : 7 }
{ "_id" : 8, "name" : "test8", "count" : 8 }
{ "_id" : 9, "name" : "test9", "count" : 9 }
{ "_id" : 10, "name" : "test10", "count" : 10 }
{ "_id" : 11, "name" : "test11", "count" : 11 }
{ "_id" : 12, "name" : "test12", "count" : 12 }
{ "_id" : 13, "name" : "test13", "count" : 13 }
{ "_id" : 14, "name" : "test14", "count" : 14 }
{ "_id" : 15, "name" : "test15", "count" : 15 }
2). update()
db.collection.update( criteria, objNew, upsert, multi ) 四個參數的說明如下:
criteria: update的查詢條件,類似sql update查詢內where後面的
objNew: update的對象和一些更新的操作符(如$,$inc...)等,也可以理解為sql update查詢內set後面的
upsert: 這個參數的意思是,如果不存在update的記錄,是否插入objNew,true為插入,預設是false,不插入。
multi: mongodb預設是false,只更新找到的第一條記錄,如果這個參數為true,就把按條件查出來多條記錄全部更新。
幾個查詢例子如下:
db.mytest.update({count:{$gt:1}},{$set:{name:"ok"}}) 只更新第一條記錄
db.mytest.update({count:{$gt:3}},{$set:{name:"ok"}},false,true) 大於3的全部更新了
db.mytest.update({count:{$gt:4}},{$set:{name:"ok123"}},true,false) 只更新了一條
db.mytest.update({count:{$gt:6}},{$set:{name:"ok123"}},true,true) 大於6的全部更新了
3). save()
db.collection.save(x) x是要插入的對象,效果與上面的insert命令一樣。save與insert的區別是這樣的:
在進行插入資料的操作中,當遇到_id相同的情況下,save完成儲存操作,insert則會儲存;即_id相同情況下,save相當於更新操作。
下面是一些MongoDB的更新操作符
更多詳情見請繼續閱讀下一頁的精彩內容:
MongoDB 的詳細介紹:請點這裡
MongoDB 的:請點這裡
推薦閱讀:
Java實現MongoDB中自增長欄位
CentOS編譯安裝MongoDB
CentOS 編譯安裝 MongoDB與mongoDB的php擴充
CentOS 6 使用 yum 安裝MongoDB及伺服器端配置
Ubuntu 13.04下安裝MongoDB2.4.3
如何在MongoDB中建立新資料庫和集合
MongoDB入門必讀(概念與實戰並重)
《MongoDB 權威指南》(MongoDB: The Definitive Guide)英文文字版[PDF]