以博文与评论为例,博文有标题内容,对应多个评论,评论有评论人、评论内容等。 ()插入一条博文:
db.blog.insert(
{'_id':'','title':'this is blog title1','content':'this is blog content1'}
) ()更新一条博文
db.blog.update(
{'_id':''},
{$set:{'title':'this is blog title2','content':'this is blog content2'}}
) ()更新一条博文,如果不存在就插入
db.blog.update(
{'_id':''},
{$set:{'title':'this is blog title4','content':'this is blog content4'}},
{upsert:true}
) ()对博文增加一条评论内容
db.blog.update(
{'_id':''},
{$push:{'comments':{'user':'user1','content':'评论1'}}}
) ()根据条件删除博文的评论
db.blog.update(
{'_id':''},
{$pull:{'comments':{'user':'user1'}}}
) ()使用$addToSet避免添加重复数据
db.blog.update(
{'_id':''},
{$addToSet:{'comments':{'user':'user1','content':'评论1'}}}
) ()用$addToSet & $each联合操作批量插入数据
db.blog.update(
{'_id':''},
{$addToSet:{'comments':{'$each':[
{'user':'user1','content':'评论1'},
{'user':'user2','content':'评论2'},
{'user':'user3','content':'评论3'},
]}}}
)