1024programmer Java MongoDBinsert/update/one2many case

MongoDBinsert/update/one2many case

Take blog posts and comments as an example. A blog post has a title content, which corresponds to multiple comments, and a comment has a commentator, comment content, etc.

 (1)Insert a blog post:
 db.blog.insert(
     {'_id':'11'  ,'title':'this is blog title1','content':'this is blog content1'}
 )

 (2) Update a blog post
 db.blog.update(
     {'_id':'11'  },
     {$set:{'title':'this is blog title2','content':'this is  blog content2'}}
 )

 (3) Update a blog post and insert it if it does not exist
 db.blog.update(
     {'_id':'12'  },
     {$set:{'title':'this is blog title4','content':'this is  blog content4'}},
     {upsert:true}
 )

 (4) Add a comment to the blog post
 db.blog.update(
     {'_id':'11'  },
     {$push:{'comments':{'user':'user1','content':'Comment 1'}}}
 )

 (5) Delete blog post comments based on conditions
 db.blog.update(
     {'_id':'11'  },
     {$pull:{'comments':{'user':'user1'}}}
 )


 (6) Use $addToSet to avoid adding duplicate data
 db.blog.update(
    {'_id':'11'  },
    {$addToSet:{'comments':{'user':'user1','content':'Comment 1'}}}
 )

 (7) Use $addToSet & $each joint operation to insert data in batches
 db.blog.update(
    {'_id':'11'  },
    {$addToSet:{'comments':{'$each':[
     {'user':'user1'  ,'content':'Comment 1  '},
     {'user':'user2'  ,'content':'Comment 2  '},
     {'user':'user3'  ,'content':'Comment 3  '},
    ]}}}
 )

MongoDB insert/update/one2many case


This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/736960

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索