node.js连接MongoDB,获取A字段并截取字段值复制到B字段

1.新建test.js,分别执行MongoDB的查找和更新操作

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://ip:27017/";
 
MongoClient.connect(url, {
    
     useNewUrlParser: true }, function(err, db) {
    
    
    if (err) throw err;
    var dbo = db.db("IntelligentGuidance");
 var SID = "";
 var SNAME = "";
 var whereStr ="";
 var updateStr = "";
    dbo.collection("disease_info"). find({
    
    }).toArray(function(err, result) {
    
     // 返回集合中所有数据
        if (err) throw err;
        console.log(result);
  console.log(result.length);
  //遍历取出所有数据
  for(i=0,len=result.length; i<len; i++ ){
    
    
   var SICK_ID = result[i].SICK_ID;
   var sickid_length = SICK_ID.length;
   
   //取SNAME值
   SNAME = SICK_ID.substring(sickid_length-3,sickid_length);
   console.log(SNAME);
   
   //取SID值
   SID = SICK_ID.substring(0,sickid_length-3);
   console.log("SID = " + SID);
   
   //更新数据库
   whereStr = {
    
    "SICK_ID":SICK_ID};  // 查询条件
   updateStr = {
    
    $set: {
    
     
   "SNAME" : SNAME,
   "SID" : SID
   }};
   dbo.collection("disease_info").updateOne(whereStr, updateStr, function(err, res) {
    
    
   if (err) throw err;
   console.log("文档更新成功");
   db.close();
    });
  }
  //console.log(SID);  
 
        db.close();
    });
});

2.node运行test.js
在这里插入图片描述
3.MongoDB数据库内显示
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40550118/article/details/105220257