您好,登錄后才能下訂單哦!
MongoDB中文檔存入數據庫后用update方法更新文檔,update方法有兩個參數,例如
update(args1,args2)
args1是指查詢文檔的條件;
args2是指對查詢到的文檔進行什么樣的修改;
一、文檔替換
> joe1= db.post.findOne({"age":20}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 20 } > joe1.age=21 21 > db.post.update({"id":1},joe1) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) >
修改后的結果:
> joe1= db.post.findOne({"age":21}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21 } >
二、使用修改器
1.$set修改器
$set用來指定一個字段的值,如果字段不存在就創建;
> db.post.findOne() { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65 }
增加comments的鍵:
> db.post.update({"id":0}, ... {$set:{"comments":"i love you"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne() { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65, "comments" : "i love you" } >
修改comments鍵的值:
> db.post.update({"id":0}, {$set:{"comments":"i don't love you"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne() { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65, "comments" : "i don't love you" } >
修改comments的值為數組:
> db.post.update({"id":0}, {$set:{"comments":["i love you","or","i don't love you"]}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":0}) { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65, "comments" : [ "i love you", "or", "i don't love you" ] } >
刪除comments的值:
> db.post.update({"id":0}, {$unset:{"comments":1}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":0}) { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65 } >
2.修改內嵌文檔
> db.post.findOne({"id":0}) { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65, "comments" : { "1" : 1, "2" : 2, "3" : 3 } } > db.post.update({"id":0}, {$set:{"comments.1":4}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":0}) { "_id" : ObjectId("54a530c3ff0df3732bac167f"), "id" : 0, "name" : "joe", "age" : 65, "comments" : { "1" : 4, "2" : 2, "3" : 3 } } >
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。