【MongoDB學習筆記5】MongoDB中的建立、讀取、更新、刪除(CRUD)

來源:互聯網
上載者:User

標籤:crud   mongodb   

資料庫會用到建立(create)讀取(find)更新(update)刪除(remove),MongoDB也同樣會用到;

 

一、建立

用insert函數將文檔添加到集合中。例如

建立資料庫blog,將文檔增加到集合post中(先將文檔放入post的變數中)

> post={"title":"My blog post","context":"Here‘s my blog post","date":new Date()}   > use blog    switched to db blog    > db.post.insert(post);    WriteResult({ "nInserted" : 1 })

 

二、讀取

用find方法或者findone方法查看集合中的文檔,例如

> db.post.find()   { "_id" : ObjectId("54a50253e287e09898eab58b"), "title" : "My blog post", "context" : "Here‘s my blog post", "date" : ISODate("2015-01-01T08:15:14.121Z") }    > db.post.findOne()    {            "_id" : ObjectId("54a50253e287e09898eab58b"),            "title" : "My blog post",            "context" : "Here‘s my blog post",            "date" : ISODate("2015-01-01T08:15:14.121Z")    }    >

 

三、更新

重新給變數post賦值

> use blog   switched to db blog    > post=db.post.findOne()    {            "_id" : ObjectId("54a50253e287e09898eab58b"),            "title" : "My blog post",            "context" : "Here‘s my blog post",            "date" : ISODate("2015-01-01T08:15:14.121Z")    }

給變數post增加一個comments文檔  

> post.comments = []    [ ]

update方法更新集合  

> db.post.update({"title":"My blog post"},post)    ;WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })    > db.post.findOne()    {            "_id" : ObjectId("54a50253e287e09898eab58b"),            "title" : "My blog post",            "context" : "Here‘s my blog post",            "date" : ISODate("2015-01-01T08:15:14.121Z"),            "comments" : [ ]    }

   

四、刪除

用removed方法刪除文檔

> db.post.remove({"title":"My blog post"});   WriteResult({ "nRemoved" : 1 })    > db.post.findOne();    null    >

   

刪除後post集合為空白;


本文出自 “緣隨心愿” 部落格,請務必保留此出處http://281816327.blog.51cto.com/907015/1598289

【MongoDB學習筆記5】MongoDB中的建立、讀取、更新、刪除(CRUD)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.