MongoDB insert/update/one2many案例

來源:互聯網
上載者:User

標籤:

以博文與評論為例,博文有標題內容,對應多個評論,評論有評論人、評論內容等。(1)插入一條博文:db.blog.insert(    {‘_id‘:‘11‘,‘title‘:‘this is blog title1‘,‘content‘:‘this is blog content1‘})(2)更新一條博文db.blog.update(    {‘_id‘:‘11‘},    {$set:{‘title‘:‘this is blog title2‘,‘content‘:‘this is blog content2‘}})(3)更新一條博文,如果不存在就插入db.blog.update(    {‘_id‘:‘12‘},    {$set:{‘title‘:‘this is blog title4‘,‘content‘:‘this is blog content4‘}},    {upsert:true})(4)對博文增加一條評論內容db.blog.update(    {‘_id‘:‘11‘},    {$push:{‘comments‘:{‘user‘:‘user1‘,‘content‘:‘評論1‘}}})(5)根據條件刪除博文的評論db.blog.update(    {‘_id‘:‘11‘},    {$pull:{‘comments‘:{‘user‘:‘user1‘}}})(6)使用$addToSet避免添加重複資料db.blog.update(   {‘_id‘:‘11‘},   {$addToSet:{‘comments‘:{‘user‘:‘user1‘,‘content‘:‘評論1‘}}})(7)用$addToSet & $each聯合操作批量插入資料db.blog.update(   {‘_id‘:‘11‘},   {$addToSet:{‘comments‘:{‘$each‘:[    {‘user‘:‘user1‘,‘content‘:‘評論1‘},    {‘user‘:‘user2‘,‘content‘:‘評論2‘},    {‘user‘:‘user3‘,‘content‘:‘評論3‘},   ]}}})

 

MongoDB insert/update/one2many案例

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.