7.2电商数据模型更新
update时{multi:true}的参数的使用:
{multi:true},它允许对所有匹配的文档执行更新,如果没有{multi:true},则只会更新第一个匹配的文档。
位置操作符$的使用(下标)
db.users.update({
... 'addresses.name':'work'},
... {$set:{'addresses.$.street':'12 E.23rd Street'}}
... )users中的addresses是一个数组,匹配到'addresses.name':'work'对象的下标为1,所以使用addresses.$,其中$指代匹配到的下标。不使用$会报错。
往评价表添加有效评价(需要过滤已经评价过的)
query_selector = {
... '_id':'4c4b1476238d3b4dd5000041',
... 'voter_ids':{$ne:'4c4b1476238d3b4dd5000001'}
... }
db.reviews.update(query_selector,{
... $push:{'voter_ids':'4c4b1476238d3b4dd5000001'},
... $inc:{helpful_votes:1}
... })使用了目标更新来记录用户的投票。$ne用来确保、过滤重复评价。$push操作符添加投票者ID到数组中。并使用$inc增加投票的数量。
更新订单(更新文档通过商品价格增加订单的总额)
cart_item = {
... '_id':'4c4b1476238d3b4dd50003981',
... 'slug':'wheel-barrow-9092',
... 'sku':9092,
... 'name':'Extra Large Wheelbarrow',
... 'pricing':{'retail':589700,'sale':489700}
... }
selector = {
... 'user_id': '4c4b1476238d3b4dd5000001',
... 'state': 'CART'
... }
update = {
... $inc:{'sub_total': cart_item['pricing']['sale']}
... }
db.orders.update(selector, update,{upsert:true})upsert,如果文档不存在,那么upsert将会创建文档。
更新订单(更新line_items)
cart_item = {
... '_id':'4c4b1476238d3b4dd50003981',
... 'slug':'wheel-barrow-9092',
... 'sku':9092,
... 'name':'Extra Large Wheelbarrow',
... 'pricing':{'retail':589700,'sale':489700}
... }
selector = {
... 'state': 'CART',
... 'line_items._id':{$ne: cart_item._id}
... }
update = {$push:{'line_items':cart_item}}
{
"$push" : {
"line_items" : {
"_id" : "4c4b1476238d3b4dd50003981",
"slug" : "wheel-barrow-9092",
"sku" : 9092,
"name" : "Extra Large Wheelbarrow",
"pricing" : {
"retail" : 589700,
"sale" : 489700
}
}
}
}
db.orders.update(selector, update)

浙公网安备 33010602011771号