好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

5.mongoDB更新操作

" qty " : { $lt: 50 } }, { $ set : { " size.uom " : " in " , status: " P " }, $currentDate: { lastModified: true } } )
"P"   文档里面的 "size.uom"   都更新为 "in"
   

字段解释:

1.$set用于更新值:它会更新所有status为‘p‘的文档,把符合条件的文档里的‘size测试数据’设置为:in 。

2.$currentDate指定当前的数据需要改变的状态,需要设置为true,才能更新。

 

看似很简单,但是我需要先做字符串截取,比如:

 let origin =  ‘  http://we-teach.humianyuan.cn/t1.jpg  ‘  //  原始值 
 let alter =  ‘  https://we-teach-space.humianyuan.cn/t1.jpg  ‘  //  更新后的值 
 let afterAlter =  ‘  https://we-teach-space  ‘ +origin.slice( 15 ) //  所以需要使用字符段截取 

 

但是mongo可能没有字符段截取的函数,因为我也刚刚学这个,不清楚它有没有,所以我无法对所有符合条件的值进行字符段截取,可能原生mongo可以使用正则匹配到每一个需要修改的值,然后再逐条更新,但是苦于我的正则表达式还是一窍不通,因为没有系统学过,后期得补上,所以正则匹配不适合我,所以菜鸡的我只能使用mongoose,连接数据库,再使用JS进行处理,JS使用filter遍历每一条数据,然后再逐条update:

例子:

 Teachers.find(function(err,docs){
    if  (err){
    console.log(err)
  }  else  {
    docs.filter(function(curentV){
      img  =  ‘  https://we-teach-space  ‘ + (curentV.avatar.slice( 15  ));
      _id  =  curentV._id;
        //   console.log(curentV.avatar)
        //   console.log(img) 
       Teachers.updateOne({
        $  set : { ‘  avatar  ‘  :img},
        $currentDate: { lastModified:   true   }
   }).exec(function(err,docs){
       if  (err){
       console.log(err)
       console.log(  "  出错啦  "  )
     }  else  {
       console.log(  "  更新状态:  " + docs)
     }
   })
  })
 }
}) 

 

后续例子待补……

 

5.mongoDB更新操作

标签:连接数据库   bsp   更新   ice   com   例子   new   字符   style   

查看更多关于5.mongoDB更新操作的详细内容...

  阅读:29次