標籤:
以博文與評論為例,博文有標題內容,對應多個評論,評論有評論人、評論內容等。(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案例