MongoDB創建\更新\刪除文檔操作

iddi5896 8年前發布 | 7K 次閱讀 Shell MongoDB


一、插入\創建文檔


--當插入一個不存在的文檔時,會自動創建一個文檔

[root@racdb ~]# mongo

MongoDB shell version: 2.4.14

connecting to: test

> show collections

> db.cols.insert({bar:"baz"})

> db.cols.find()

{ "_id" :ObjectId("56aac1df4e61b6d9f84d17e0"), "bar" :"baz" }

 

二、刪除文檔

--刪除所有文檔

> db.cols.remove()

--刪除符合條件的文檔

> db.cols.remove({bar:"baz"})

 

注意:db.cols.remove()不會刪除cols集合本身,原有索引也會保留

 

三、更新文檔

 

文檔替換

 

--如果把下面文檔

>db.users.findOne({"name":"licz"})

{

       "_id" : ObjectId("56a8828b308203e00e436b01"),

       "name" : "licz",

       "friends" : 43,

       "enemies" : 5

}

 

--更新成下面文檔

{

       "_id" : ObjectId("56a8828b308203e00e436b01"),

       "relationships" : {

                "friends" : 43,

                "enemies" : 5

       },

       "username" : "licz"

}

 

更新方法:

> licz.relationships ={"friends":licz.friends,"enemies":licz.enemies}

{ "friends" : 43,"enemies" : 5 }

> licz.username = licz.name

licz

> delete licz.friends

true

> delete licz.enemies

true

> delete licz.name

true

>db.users.findOne({"name":"licz"})

{

       "_id" : ObjectId("56a8828b308203e00e436b01"),

       "name" : "licz",

       "friends" : 43,

       "enemies" : 5

}

>db.users.update({name:"licz"},licz)

>db.users.findOne({"username":"licz"})

{

       "_id" : ObjectId("56a8828b308203e00e436b01"),

       "relationships" : {

                "friends" : 43,

                "enemies" : 5

       },

       "username" : "licz"

}

 

使用修改器

 

1. $set

$set用來修改指定鍵的值,如果鍵不存在,就創建它。

>db.users.findOne({"name":"haley"})

{

       "_id" : ObjectId("4b253b067525f35f94b60a31"),

       "name" : "haley",

       "age" : 30,

       "sex" : "male"

}

 

--增加文檔的鍵值對

> db.users.update({"name":"haley"},{"$set":{"location":"china"}})

> db.users.update({"name":"haley"},{"$set":{"favoritebook":"war and peace"}})

>db.users.findOne({"name":"haley"})

{

       "_id" : ObjectId("4b253b067525f35f94b60a31"),

       "name" : "haley",

       "age" : 30,

       "sex" : "male",

       "location" : "china",

       "favorite book" : "war and peace"

}

--修改"favoritebook"鍵的值

> db.users.update({"name":"haley"},{"$set":{"favoritebook":"green eggs and ham"}})

>db.users.findOne({"name":"haley"})

{

       "_id" : ObjectId("4b253b067525f35f94b60a31"),

       "name" : "haley",

       "age" : 30,

       "sex" : "male",

       "location" : "china",

       "favorite book" : "green eggs and ham"

}

 

2. $inc

$inc用來增加/減少文檔中鍵的值,同樣如果鍵不存在,就創建它

>db.analytics.findOne({"url":"www.example.com"})

{

       "_id" : ObjectId("4b253b067525f35f94b60a31"),

       "url" : "www.example.com",

       "pageviews" : 54

}

>db.analytics.update({"url":"www.example.com"},{"$inc":{"pageviews":1}})

>db.analytics.findOne({"url":"www.example.com"})

{

       "_id" : ObjectId("4b253b067525f35f94b60a31"),

       "url" : "www.example.com",

       "pageviews" : 55

}

 

--增加"visits"鍵值對

>db.analytics.update({"url":"www.example.com"},{"$inc":{"visits":3}})

>db.analytics.findOne({"url":"www.example.com"})

{

       "_id" : ObjectId("4b253b067525f35f94b60a31"),

       "url" : "www.example.com",

       "pageviews" : 55,

       "visits" : 3

}

 

注意:可以看$set$inc修改器的區別:

$set是修改字符型的鍵值,$inc是修改數值型的鍵值;都是在不存在鍵時會自動添加上。

 

數據組修改器

 

3. $push

$push作用:如果指定的鍵存在,$push會向已有數組末尾加入一個元素,要是沒有就會創建一個新的數據。

>db.blog.posts.findOne({"title":"A Oracle error summary"})

{

        "_id" :ObjectId("56aad2744e61b6d9f84d17e1"),

       "title" : "A Oracle error summary",

       "content" : "..."

}

> db.blog.posts.update({"title":"AOracle error summary"},

...{"$push":{"comments":{"name":"licz","email":"licz@163.com","content":"goodpost!"}}})

 

>db.blog.posts.findOne({"title":"A Oracle error summary"})

{

       "_id" : ObjectId("56aad2744e61b6d9f84d17e1"),

       "title" : "A Oracle error summary",

       "content" :"...",

       "comments" : [

                {

                        "name" :"licz",

                        "email" :"licz@163.com",

                        "content" :"good post!"

                }

       ]

}

--再次加一個數據元素

... {"$push":{"comments":{"name":"haley","email":"haley@qq.com","content":"thankyou post"}}})

>db.blog.posts.findOne({"title":"A Oracle error summary"})

{

       "_id" : ObjectId("56aad2744e61b6d9f84d17e1"),

       "title" : "A Oracle error summary",

       "content" : "...",

       "comments" : [

                {

                        "name" :"licz",

                        "email" :"licz@163.com",

                        "content" :"good post!"

                },

                {

                        "name" :"haley",

                        "email" :"haley@qq.com",

                        "content" :"thank you post"

                }

       ]

}

 

 

4. $ne

$ne可以對鍵做一些判斷,如:使用$ne$push組,如果一個值不在數組里面就把他加進去,避免插入重復值

 

> db.papers.findOne()

{

       "_id" : ObjectId("56aadaaa4e61b6d9f84d17e2"),

       "title" : "People life",

       "content" : "..."

}

>db.papers.update({"authorscited":{"$ne":"Richie"}},

...{"$push":{"authorscited":"Richie"}})

> db.papers.findOne()

{

       "_id" : ObjectId("56aadaaa4e61b6d9f84d17e2"),

       "title" : "People life",

       "content" : "...",

       "authors cited" : [

                "Richie"

       ]

}

--再次加入相同元素,文檔沒有變化

> db.papers.update({"authorscited":{"$ne":"Richie"}},

...{"$push":{"authorscited":"Richie"}})

> db.papers.findOne()

{

       "_id" : ObjectId("56aadaaa4e61b6d9f84d17e2"),

       "title" : "People life",

       "content" : "...",

       "authors cited" : [

                "Richie"

       ]

}

 

5. $addToSet

$addToSet作用:可以代替$ne$push組全,在數組里加入一個元素且能加入多個元素,也能避免插入重復值

 

>db.users.findOne({"username":"licz"}

{

       "_id" : ObjectId("56a8828b308203e00e436b01"),

       "relationships" : {

                "friends" : 43,

                "enemies" : 5

       },

        "username" : "licz"

}

> db.users.update({"username":"licz"},{"$addToSet":{"email":"licz@163.com"}})

>db.users.findOne({"username":"licz"})

{

       "_id" : ObjectId("56a8828b308203e00e436b01"),

       "relationships" : {

                "friends" : 43,

                "enemies" : 5

       },

       "username" : "licz",

       "email" : [

                "licz@163.com"

       ]

}

 

--再執行增加數組元素

> db.users.update({"username":"licz"},{"$addToSet":{"email":"licz@qq.com"}})

> db.users.findOne({"username":"licz"})

{

       "_id" : ObjectId("56a8828b308203e00e436b01"),

       "relationships" : {

                "friends" : 43,

                "enemies" : 5

       },

       "username" : "licz",

       "email" : [

                "licz@163.com",

               "licz@qq.com"

       ]

}

 

6. $each

$addToSet$each組合,可以為數組添加多個不同的值

> db.users.update({"username":"licz"},

...{"$addToSet":{"email":{"$each":["licz@umessage.com","licz@sina.com"]}}})

>db.users.findOne({"username":"licz"})

{

       "_id" : ObjectId("56a8828b308203e00e436b01"),

       "relationships" : {

                "friends" : 43,

                "enemies" : 5

       },

       "username" : "licz",

       "email" : [

                "licz@163.com",

                "licz@qq.com",

                "licz@umessage.com",

                "licz@sina.com"

       ]

}

 

7. $pop

$pop修改器可以從數組任何一端刪除元素。

{$pop:{key:1}}從末尾端刪除元素

{$pop:{key:-1}}從開頭端刪除元素

 

8. $pull

$pull可以基于特定條件來刪除數組元素,而不僅僅是依據位置

>db.lists.insert({"todo":["dishs","laundry","drycleaning"]})

> db.lists.update({},{"$pull":{"todo":"laundry"}})

> db.lists.findOne()

{

       "_id" : ObjectId("56aafd4a4e61b6d9f84d17e3"),

       "todo" : [

                "dishs",

                "dry cleaning"

       ]

}

 

$pull會將所有匹配的部分刪掉。對數組[1,1,2,1]執行pull 1,得到的結果是只有一個元素[2]

 

數組的定位修改器

有兩種方法操作數組中的值:通過位置和定位操作符$

數組都是以0開頭的,可以直接用下標直接作為鍵來選擇元素,如下

>db.blog.posts.findOne({"title" : "A blog post"})

{

       "_id" : ObjectId("4b2d75476cc613d5ee930164"),

       "title" : "A blog post",

       "content" : "...",

       "comments" : [

                {

                        "name" :"joe",

                        "email" :"joe@example.com",

                        "content" :"nice post."

                },

                {

                        "name" :"bob",

                        "email" :"bob@example.com",

                        "content" :"good post."

                }

       ]

}

>db.blog.posts.update({"title" : "A blogpost"},{"$inc":{"comments.0.visits" : 1}})

>db.blog.posts.findOne({"title" : "A blog post"})

{

       "_id" : ObjectId("4b2d75476cc613d5ee930164"),

       "title" : "A blog post",

       "content" : "...",

       "comments" : [

                {

                        "name" :"joe",

                        "email" :"joe@example.com",

                        "content" :"nice post.",

                        "visits" : 1

                },

                {

                        "name" :"bob",

                        "email" :"bob@example.com",

                        "content" : "goodpost."

                }

       ]

}

 

但很多情況我們不知道要修改數組下標是多少,這時就可以使用定位操作符$,用來定位查詢文檔已經匹配的元素,并進行更新。

>db.blog.posts.update({"comments.name":"bob"},{"$set":{"comments.$.name":"licz"}})

>db.blog.posts.findOne({"title" : "A blog post"})

{

       "_id" : ObjectId("4b2d75476cc613d5ee930164"),

       "title" : "A blog post",

       "content" : "...",

       "comments" : [

                {

                        "name" :"joe",

                        "email" :"joe@example.com",

                        "content" :"nice post.",

                        "visits" : 1

                },

                {

                        "name" :"licz",

                        "email" :"bob@example.com",

                        "content" :"good post."

                }

       ]

}

 

upsert更新方法

upsert是一種特殊的更新。要是沒有文檔符合更新條件,就會以這個條件創建一個新文檔,如果匹配就更新。其實就是update的第三參數,默認就是false.

> db.analytics.find()

{ "_id" :ObjectId("56a88706308203e00e436b04"), "url" :"www.baidu.com", "pageview" : 2, "visits" : 3 }

> db.analytics.update({"url":"www.csdn.net"},{"$inc":{"visits": 1}},true)

> db.analytics.find()

{ "_id" :ObjectId("56a88706308203e00e436b04"), "url" :"www.baidu.com", "pageview" : 2, "visits" : 3 }

{ "_id" :ObjectId("56ab094c638a1346c373d5d9"), "url" :"www.csdn.net", "visits" : 1 }

 

save 函數

save是一個shell函數,可以文檔不存在時插入,存在時更新。它只有一個參數:文檔

使用如下:

> var x=db.foo.findOne()

> x.sum = 50

50

> db.foo.save(x)

> db.foo.find()

{ "_id" :ObjectId("56a88f55308203e00e436b07"), "count" :"1", "num" : 42, "sum" : 50 }

 

 

更新更多的文檔

默認情況下,更新只能對條件的第一個文檔執行操作。要使用所有文檔都得到更新,可以設置update的第4個參數為ture,默認是false

例如:

給所有特定日期過生日的用戶發一份禮物,就可使用多文檔更新,將gift增加到他們的賬號.

 

>db.users.update({"birthday":"1988/11/1"},{"$set":{gift:"Happybirthday!"}},false,true)

 

--查看更新了多少文檔,n就是這個值

> db.runCommand({getLastError : 1})

{

       "connectionId" : 13,

       "n" : 3,

       "syncMillis" : 0,

       "writtenTo" : null,

       "err" : null,

       "ok" : 1

}

 

 本文由用戶 iddi5896 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!