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案例
标签:
查看更多关于MongoDB insert/update/one2many案例的详细内容...