你越是认真生活,你的生活就会越美好——弗兰克·劳埃德·莱特
《人生果实》经典语录

mongodb shell 运行js脚本的四种方式

mongo shell

大部分的 mongodb 教程,在第一章都会讲解这种方式。

mongo 127.0.0.1:27017/test
// 默认链接127.0.0.1:27017  test数据库
mongo
use infinite-lightning
db.users.find({name:"陈坚泓"}).pretty()
db.users.findOne({name:"陈坚泓"})

pretty() 可以让展示的数据有规则展示,美观一些
在这里插入图片描述

mongo --eval 运行一段脚本

不进入mongo shell交互模式,直接在命令行下运行一段mongodb脚本

mongo 127.0.0.1:27017/infinite-lightning --eval "printjson(db.users.findOne({name:'陈坚泓'}))"

在这里插入图片描述

MongoDB服务器端可以通过db.eval函数执行javascript脚本,如我们可以定义一个javascript函数,然后通过db.eval在服务器端来运行!

在服务器端可以通过db.eval函数来执行javascript脚本,也可以把javascript脚本保存数据库中,然后在别的数据库命令中调用

MongoDB Shell通过db.eval 执行JS脚本

利用db.eval函数可以在MongoDB服务器端执行javascript脚本.这个函数先将给定的javascript字符串传递给MongoDB服务器,在服务器上执行,然后返回结果.

db.eval可以用来模拟多文档事务:
db.eval锁住数据库,然后执行javascript,再解锁.虽然没有内置的回滚机制,但这能确保一系列操作按照指定的数序发生.
发送代码有两种方式,封装一个函数或者不封装,如:

db.eval("return 'refactor';")
db.eval("function(){return 'refactor';}")

在这里插入图片描述

存储javascript

每个MongoDB的数据库中都有个特殊的集合:system.js,用来存放javascript变量.这些变量可以在任何MongoDB的javascript上下文中调用,包括"$where"子句,db.eval调用,MapReduce作业.用insert可以将变量存在system.js中

db.system.js.insert({"_id":"x","value":1})
db.system.js.insert({"_id":"y","value":2})
db.system.js.insert({"_id":"z","value":3})

上例在全局作用域中定义了x,y,z,对其求和:

db.eval("return x+y+z;")

在这里插入图片描述

在mongo shell 交互模式下,运行一个js文件

mongo infinite-lightning

在这里插入图片描述

load("C:/Users/chen/Desktop/userfindone.js")

在这里插入图片描述

load() 参数中的文件路径,既可以是相对路径,也可以是绝对路径
mongo shell下查看当前工作路径的方法:
pwd()
当前工作路径就是我们启动mongo shell时,当前用户所处的路径。
在这里插入图片描述

在命令行下,运行一个js文件

mongo 127.0.0.1:27017/infinite-lightning userfindone.js

userfindone.js 的内容:

printjson(db.users.findOne({name: '陈坚泓'}));

在这里插入图片描述

在js文件中建立数据库连接,数据库操作

上面所有的例子,都是在运行mongo命令时,直接连接数据库 (127.0.0.1:27017/infinite-lightning)。

我们也可以在js脚本中建立数据库连接,上面的第三种方法可以这么写:
`userfindone.js 文件内容:

conn = new Mongo("127.0.0.1:27017");
db = conn.getDB("infinite-lightning");
printjson(db.users.findOne({name:"陈坚泓"}));

在命令行下运行js文件:

mongo --nodb userfindone.js

在这里插入图片描述

注意:
以上所有命令,如果连接的数据库是127.0.0.1:27017 ,则主机和端口可以省略,例如:
mongo infinite-lightning --eval "printjson(db.users.findOne({name:"陈坚泓"}))"
文件地址同样可以是相对地址,也可以是绝对地址

命令行执行js脚本实例

命令行执行js文件,实现数据库迁移

// mongo --nodb C:/Users/chen/Desktop/puppeteer/IC-融合/localTest/demo.js
// db.collections.insert
// save 如果有内容了,则会更新,否则会新建

conn = new Mongo("127.0.0.1:27017");
db = conn.getDB("infinite-lightning");

// 要迁移的ID
var produce_company_id = "76"

// 活动表 activities相关处理
var activities = function () {
  // 活动表去重相同正式线企业id活动id,留下最新一条
  var res = db.act.find({
    produce_company_id
  });
  print(produce_company_id + '企业:' + 'activities文档数量:' + db.act.find().count())
  while (res.hasNext()) {
    var res1 = db.act.find({
      produce_company_id
    });
    // print('第一个whtie res.next():')
    var re = res.next();
    // printjson(re)
    while (res1.hasNext()) {
      var re1 = res1.next();
      // print('第二个white  res1.next():')
      // printjson(re1)
      if (
        re.produce_company_id == re1.produce_company_id &&
        re.produce_activity_id == re1.produce_activity_id &&
        parseInt(re.create_time) > parseInt(re1.create_time)
      ) {
        db.act.remove({
          "_id": re1._id,
          "create_time": re1.create_time
        });
      }
    }
  }
  // 活动表去重相同统计id,留下最新一条
  var res = db.act.find({
    produce_company_id
  });
  while (res.hasNext()) {
    var res1 = db.act.find({
      produce_company_id
    });
    var re = res.next();
    while (res1.hasNext()) {
      var re1 = res1.next();
      if (re.statistics_id == re1.statistics_id && parseInt(re.create_time) > parseInt(re1.create_time)) {
        db.act.remove({
          "_id": re1._id,
          "create_time": re1.create_time
        });
      }
    }
  }

  // 活动迁移表 
  var res = db.act.find({
    produce_company_id
  });
  // num: 迁移的集合数量
  var num = 0; 
  while (res.hasNext()) {
    var re = res.next();
    try {
      // insertOne 改用 save  save如果存在会更新
      db.activities.insertOne({
        _id: re._id,
        template: re.template,
        produce_company_id: NumberInt(parseInt(re.produce_company_id)),
        produce_activity_id: NumberInt(parseInt(re.produce_activity_id)),
        test_activity_id: NumberInt(parseInt(re.test_activity_id)),
        test_company_id: NumberInt(parseInt(re.test_company_id)),
        description: re.description,
        title: re.name,
        thumbnail: re.thumbnail,
        test_status: NumberInt(0),
        statistics_id: re.statistics_id,
        config: re.config
      });
      num++
    } catch (e) {
      print('db.activities.insertOne catch()')
      print(re._id)
    }
  }
  print('activities insertOne数量:' + num)
  // 删除过渡表
  // db.act.drop()
}

// 活动发布历史表 activityhistories相关处理
var activityhistories = function () {
  print('活动发布历史文档数量:' + db.acthistory.find().count())
  var num = 0;
  // var produce_company_id = 2
  try {
    var act = db.act.find({
      produce_company_id
    })
    print('企业:' + produce_company_id + 'activities文档数量:' + act.count())
    var activities = db.act.find()
    print('activities文档数量:' + activities.count())
    while(act.hasNext()) {
      var _act = act.next()
      print(`_act._id:` + _act._id)
      var re = db.histories.find({
        activity_id: _act._id
      })
      print('根据万花筒活动id匹配到的活动发布历史文档数量')
      printjson(re.count())
      while(re.hasNext()) {
        var _re = re.next()
        // printjson(`_re.activity_id:` + _re.activity_id)
        try {
          db.activityhistories.insertOne({
            _id: _re._id,
            wht_activity_id: _re.activity_id,
            user: _re.user,
            config: _re.config,
            remarks: _re.remarks,
            create_time: NumberInt(_re.create_time)
          })
          num++
        } catch(e) {
          print('db.activityhistories.insertOne catch(e) e')
          print(e._id)
        }
      }
    }
    
  } catch (e) {
    print('activityhistories 出错')
    // printjson(e)
    // print(re._id)
  }
  print('activityhistories 企业' + produce_company_id + 'insertOne数量:'  + num)
  // 删除过渡表
  db.act.drop()
  db.acthistory.drop()
}


// 模板表 templates相关处理 
var templates = function () {
  // <!-- // 模版表去重 相同名字 根据create_time 只保留最新的 -->
  var res = db.tem.find();
  var temNum1 = 0
  var temNum2 = 0
  var temNum3 = 0
  var temNum4 = 0 // 删除的数量
  var temNum5 = 0 // catch 到的数量
  var temNum6 = 0 // 不符合去重条件的文档数量
  var temNum7 = 0 // 累计执行次数
  var temNum8 = 0 // 去重模板数量
  var templateNameArr = []; // 用来存去重过的模板 正常一个模板循环去重过一次 就只剩下一个
  var isRemoveTem = false; // 该模板是否去重过
  print('templates  res文档数量:' + res.count())
  while (res.hasNext()) {
    temNum1++
    temNum2 = 0
    // var res1 = db.tem.find();
    var _res = res.next();
    var res2 = db.tem.find({
      'name': _res.name
    });
    if (templateNameArr.indexOf(_res.name) > -1) {
      // 该模板名已经去重过
      isRemoveTem = true
    } else {
      // 该模板名还没去重过
      isRemoveTem = false
      temNum8++
      templateNameArr.push(_res.name)
      templateNameArr.sort()
    }
    while (!isRemoveTem && res2.hasNext()) {
      temNum3 = 0
      temNum2++
      var _res2 = res2.next()
      var res3 = db.tem.find({
        name: _res2.name
      });
      // print('模板名称:' + _res2.name + '该模板名文档数量:' + res3.count())
      while (res3.hasNext()) {
        var _res3 = res3.next()
        temNum3++
        temNum7++ 
        if (temNum7 % 500 === 0) {
          print('累计执行次数 temNum7:' + temNum7)
        }
        if (temNum3 % 50 === 0) {
          print('模板名称:' + _res2.name + '该模板名文档数量:' + res3.count())
          print('tem:' + temNum1 + ' - ' + temNum2 + ' - ' + temNum3)
        }
        try {
          if (
            (_res2._id.toString().slice(-5) !== _res3._id.toString().slice(-5))
          ) {
            temNum4++
            // print('有符合条件的重复的tem 删除较早的')
            if ((parseInt(_res2.create_time) > parseInt(_res3.create_time))) {
              try {
                db.tem.remove({
                  "name": _res3.name,
                  "create_time": _res3.create_time
                });
                
                
              } catch (e) {
                print(_res3.name + '-' + _res3._id)
              }
            } else {
              try {
                db.tem.remove({
                  "name": _res2.name,
                  "create_time": _res2.create_time
                });
                _res2 = _res3
              } catch (e) {
                print(_res3.name + '-' + _res3._id)
              }
            }
            if (temNum4 % 1000 === 0) {
              print('删除重复模板名' + _res3.name + '  删除重复数量 temNum4:' + temNum4)
            }
            
          } else {
            temNum6++
            if (temNum6 % 1000 === 0) {
              print('tem没有符合条件需要去重的模板 模板名:' + _res3.name + '   ' + '累计数量temNum6:' + temNum6)
            }
          }
        } catch (e) {
          temNum5++
          print(e)
          print('catch 数量:' + temNum5 + ' - ' + _res3.name + '-' + _res3._id)
        }

      }
    }

  // <!-- // 修改模版表模版时间格式为int -->
  var res = db.tem.find();

  while (res.hasNext()) {
    var re = res.next();
    try {
      db.tem.update({}, {
        $set: {
          "create_time": NumberInt(re.create_time)
        }
      }, true, true);
    } catch (e) {
      print('tem 出错')
      print(re._id)
    }

  }

  // <!-- // 模版迁移表 -->
  var res = db.tem.find();
  // num: 迁移的数量
  var num = 0;
  while (res.hasNext()) {
    var re = res.next();
    try {
      num++
      // insertOne 改 save  
      db.templates.save({
        _id: re._id,
        name: re.name,
        content: re.content,
        mark: re.mark,
        thumbnail: re.cdn,
        modifier: ObjectId("5fc9a06ebcb3cf72f271bc7a"),
        label: [],
        create_time: NumberInt(parseInt(re.create_time)),
        renew_time: NumberInt(parseInt(re.create_time)),
        config: re.config
      });
    } catch (e) {
      print('tem表 出错')
      print(re._id)
    }
    
  }
  print('迁移templates表 save文档数量:' + num)
  // 删除过渡表
  db.tem.drop()
}

// 用户表 users相关处理
var users = function () {
  // <!-- // 用户表迁移 -->
  var res = db.us.find();
  while (res.hasNext()) {
    var re = res.next();
    try {
      // 这里insertOne改为save 存在的话 就更新
      db.users.save({
        _id: re._id,
        account: re.account,
        password: re.password ? re.password : '',
        role: re.role,
        name: re.name,
        create_time: NumberInt(parseInt(re.create_time)),
        status: NumberInt(parseInt(re.status)),
        // status: re.status ? NumberInt(parseInt(re.status)) : NumberInt(1)
      });
    } catch (e) {
      print('users ')
      print(re._id)
    }

  }
  // 删除过渡表
  db.us.drop()
}

// 实验表 experiments相关处理
var experiments = function () {
  var res = db.exp.find();
  print('experiments文档数量:' + db.exp.find().count())
  var num=0; 
  while (res.hasNext()) {
    var re = res.next();
    try {
        // insert 暂时改为 save
        db.experiments.insert(re)
        num++
        if (num % 500 === 0) {
          print('db.experiments.save 数量 num:' + num)
        }
      
    } catch (e) {
      print('experiments re._id:')
      print(re._id)
      print(e)
    }

  }
  // 删除过渡表
  db.exp.drop()
}

// 素材表 sources
var sources = function () {
  var res = db.sour.find();
  var num = 0;
  print('sources文档数量:' + db.sour.find().count())
  while (res.hasNext()) {
    var re = res.next();
    db.sources.insert({
      _id: re._id,
      local_url: re.local_url,
      url: re.url,
      file_type: re.file_type,
      source_type: re.source_type, // source_type用不到 可以去掉
      classify: re.source_type,
      description: re.description,
      user: re.user,
      create_time: NumberInt(parseInt(re.create_time)),
      renew_time: NumberInt(parseInt(re.renew_time)),
      md5: re.md5 ? re.md5 : ''
    })
    num++;
    if (num % 100 === 0) {
      print('db.sources.insert() 数量:' + num)
    }
  }
  // 删除过渡表
  db.sour.drop()
}

// 组合指标表 combinations
var combinations = function () {
  var res = db.comb.find();
  while (res.hasNext()) {
    var re = res.next();
    var res2 = db.us.findOne({
      _id: re.user
    });
    if (res2) {
      var res3 = db.users.findOne({
        account: res2.account
      });
      try {
        db.combinations.insert({
          name: re.name,
          field: re.field,
          formula: re.formula,
          user: res3._id,
          comId: NumberInt(parseInt(re.comId))
        })
      } catch (e) {
        print('combinations')
        print(re._id)
      }

    }
  }
  // 删除过渡表
  db.comb.drop()
}

print('开始执行活动表 activities相关处理')
activities()
print('结束')


// 模板表 templates相关处理
print('开始 templates相关处理')
templates()
print('结束')

// 用户表 users相关处理
print('开始 users相关处理')
users()
print('结束')

// 实验表 experiments相关处理
print('开始 experiments相关处理')
experiments()
print('结束')

print('素材表 sources 开始 sources相关处理')
sources()
print('结束')

// 组合指标表 combinations
print('开始 combinations相关处理')
combinations()
print('结束')


print('活动发布历史表 activityhistories   还在测试 所以放最后')
activityhistories()
print('结束')

命令行执行shell函数(批量执行mongo shell命令)

命令行里定义 shell函数
// 函数内执行的效果,导出127.0.0.1:27017下的iceditor数据库里的activities、templates、users、experiments表(集合)到本地执行的文件夹里,格式是json
fn() { 
	mongoexport -h 127.0.0.1:27017 -d iceditor -c activities -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210108/act20210108.json; 
	mongoexport -h 127.0.0.1:27017 -d iceditor -c templates -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210108/tem20210108.json; 
	mongoexport -h 127.0.0.1:27017 -d iceditor -c users -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210108/us20210108.json; 
	mongoexport -h 127.0.0.1:27017 -d iceditor -c experiments -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210108/exp20210108.json; 
}
命令行里执行shell函数
fn

在这里插入图片描述
在这里插入图片描述

实际应用,通过shell函数一次执行完成数据库迁移所有事情

echo "定义shell函数"
fn() {
  
  echo "127.0.0.1:27017 iceditor数据库备份"
  echo "mongodump -h 127.0.0.1:27017 -d iceditor -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005" 
  echo "mongodump -h 127.0.0.1:27017 -d infinite-lightning -o  C:/Users/chen/Desktop/puppeteer/IC-融合/infinite-lightning20200124007"

  echo "数据恢复回复到本地127.0.0.1:27017 iceditor数据库"
  echo "mongorestore -h 127.0.0.1:27017:27017 -d infinite-lightning C:/Users/chen/Desktop/puppeteer/IC-融合/infinite-lightning20200124006/infinite-lightning"
  echo "mongorestore -h 127.0.0.1:27017 -d iceditor  C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/iceditor"

  echo "备份活动表 iceditor库的activities表"
  echo "活动表去重相同正式线企业id活动id,留下最新一条"
  echo "活动表去重相同统计id,留下最新一条"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c activities -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/act.json
  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c act --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/act.json
  

  echo "备份活动发布表  旧版 histories  IC融合版本 activityhistories  直接迁移"
  echo "IC融合版本 添加了 experiment/title  去除了line"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c histories -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/acthistory.json
  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c acthistory --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/acthistory.json


  echo "模板表 templates   "
  echo "模版表去重"
  echo "修改模版表模版时间格式为int"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c templates -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/tem.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c tem --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/tem.json


  echo "模板表  iC融合版本表 templatelabelcategories 旧版表 labelclassifies"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c labelclassifies -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/labelclass.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c templatelabelcategories --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/labelclass.json

  echo "模板表  iC融合版本表 templatelabels 旧版表 labels"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c labels -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/label.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c templatelabels --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/label.json


  echo "用户表 users"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c users -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/us.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c us --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/us.json


  echo "实验表 experiments"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c experiments -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/exp.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c exp --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/exp.json


  echo "可视化组件类型表 visualcomponenttypes   直接迁移"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c visualcomponenttypes -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/vt.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c visualcomponenttypes --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/vt.json


  echo "可视化组件表 visualcomponents  直接迁移"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c visualcomponents -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/v.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c visualcomponents --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/v.json


  echo "服务协议迁移 serviceagreements"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c serviceagreements -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/ser.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c serviceagreements --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/ser.json


  echo "素材分类表 sourceclassifies 不需要另外处理 直接迁移"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c sourceclassifies -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/sourcl.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c sourceclassifies --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/sourcl.json


  echo "素材表迁移 sources"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c sources -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/sour.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c sour --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/sour.json


  echo "组合指标表 combinations"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c combinations -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/comb.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c comb --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/comb.json



  echo "eventcategories  不需要另外处理 直接迁移"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c eventcategories -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/ec.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c eventcategories --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/ec.json


  echo "eventitems  不需要另外处理 直接迁移"
  mongoexport -h 127.0.0.1:27017 -d iceditor -c eventitems -o C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/ei.json

  mongoimport -h 127.0.0.1:27017 -d infinite-lightning -c eventitems --file C:/Users/chen/Desktop/puppeteer/IC-融合/localTest20210124005/localTest/ei.json


  echo "开始执行数据库迁移js脚本"
  mongo --nodb C:/Users/chen/Desktop/puppeteer/IC-融合/localTest/demo.js
  echo "结束执行数据库迁移js"
}

echo "执行shell函数"
fn


C:/Users/chen/Desktop/puppeteer/IC-融合/localTest/demo.js内容如下

// mongo --nodb C:/Users/chen/Desktop/puppeteer/IC-融合/localTest/demo.js
// db.collections.insert
// save 如果有内容了,则会更新,否则会新建

conn = new Mongo("127.0.0.1:27017");
db = conn.getDB("infinite-lightning");

// 要迁移的ID
var produce_company_id = "76"

// 活动表 activities相关处理
var activities = function () {
  // 活动表去重相同正式线企业id活动id,留下最新一条
  var res = db.act.find({
    produce_company_id
  });
  print(produce_company_id + '企业:' + 'activities文档数量:' + db.act.find().count())
  while (res.hasNext()) {
    var res1 = db.act.find({
      produce_company_id
    });
    // print('第一个whtie res.next():')
    var re = res.next();
    // printjson(re)
    while (res1.hasNext()) {
      var re1 = res1.next();
      // print('第二个white  res1.next():')
      // printjson(re1)
      if (
        re.produce_company_id == re1.produce_company_id &&
        re.produce_activity_id == re1.produce_activity_id &&
        parseInt(re.create_time) > parseInt(re1.create_time)
      ) {
        db.act.remove({
          "_id": re1._id,
          "create_time": re1.create_time
        });
      }
    }
  }

  // 活动表去重相同统计id,留下最新一条
  var res = db.act.find({
    produce_company_id
  });
  while (res.hasNext()) {
    var res1 = db.act.find({
      produce_company_id
    });
    var re = res.next();
    while (res1.hasNext()) {
      var re1 = res1.next();
      if (re.statistics_id == re1.statistics_id && parseInt(re.create_time) > parseInt(re1.create_time)) {
        db.act.remove({
          "_id": re1._id,
          "create_time": re1.create_time
        });
      }
    }
  }

  // 活动迁移表 
  var res = db.act.find({
    produce_company_id
  });
  // num: 迁移的集合数量
  var num = 0; 
  while (res.hasNext()) {
    var re = res.next();
    try {
      // insertOne 改用 save  save如果存在会更新
      db.activities.insertOne({
        _id: re._id,
        template: re.template,
        produce_company_id: NumberInt(parseInt(re.produce_company_id)),
        produce_activity_id: NumberInt(parseInt(re.produce_activity_id)),
        test_activity_id: NumberInt(parseInt(re.test_activity_id)),
        test_company_id: NumberInt(parseInt(re.test_company_id)),
        description: re.description,
        title: re.name,
        thumbnail: re.thumbnail,
        test_status: NumberInt(0),
        statistics_id: re.statistics_id,
        config: re.config
      });
      num++
    } catch (e) {
      print('db.activities.insertOne catch()')
      print(re._id)
    }

  }
  print('activities insertOne数量:' + num)
  // 删除过渡表
  // db.act.drop()
}

// 活动发布历史表 activityhistories相关处理
var activityhistories = function () {
  print('活动发布历史文档数量:' + db.acthistory.find().count())
  var num = 0;
  // var produce_company_id = 2
  try {
    var act = db.act.find({
      produce_company_id
    })
    print('企业:' + produce_company_id + 'activities文档数量:' + act.count())
    var activities = db.act.find()
    print('activities文档数量:' + activities.count())
    while(act.hasNext()) {
      var _act = act.next()
      print(`_act._id:` + _act._id)
      var re = db.histories.find({
        activity_id: _act._id
      })
      print('根据万花筒活动id匹配到的活动发布历史文档数量')
      printjson(re.count())
      while(re.hasNext()) {
        var _re = re.next()
        // printjson(`_re.activity_id:` + _re.activity_id)
        try {
          db.activityhistories.insertOne({
            _id: _re._id,
            wht_activity_id: _re.activity_id,
            user: _re.user,
            config: _re.config,
            remarks: _re.remarks,
            create_time: NumberInt(_re.create_time)
          })
          num++
        } catch(e) {
          print('db.activityhistories.insertOne catch(e) e')
          print(e._id)
        }
      }
    }
    
  } catch (e) {
    print('activityhistories 出错')
    // printjson(e)
    // print(re._id)
  }
  print('activityhistories 企业' + produce_company_id + 'insertOne数量:'  + num)
  // 删除过渡表
  db.act.drop()
  db.acthistory.drop()
}


// 模板表 templates相关处理 
var templates = function () {
  // <!-- // 模版表去重 相同名字 根据create_time 只保留最新的 -->
  var res = db.tem.find();
  var temNum1 = 0
  var temNum2 = 0
  var temNum3 = 0
  var temNum4 = 0 // 删除的数量
  var temNum5 = 0 // catch 到的数量
  var temNum6 = 0 // 不符合去重条件的文档数量
  var temNum7 = 0 // 累计执行次数
  var temNum8 = 0 // 去重模板数量
  var templateNameArr = []; // 用来存去重过的模板 正常一个模板循环去重过一次 就只剩下一个
  var isRemoveTem = false; // 该模板是否去重过
  print('templates  res文档数量:' + res.count())
  while (res.hasNext()) {
    temNum1++
    temNum2 = 0
    // var res1 = db.tem.find();
    var _res = res.next();
    var res2 = db.tem.find({
      'name': _res.name
    });
    if (templateNameArr.indexOf(_res.name) > -1) {
      // 该模板名已经去重过
      isRemoveTem = true
    } else {
      // 该模板名还没去重过
      isRemoveTem = false
      temNum8++
      templateNameArr.push(_res.name)
      templateNameArr.sort()
    }
    while (!isRemoveTem && res2.hasNext()) {
      temNum3 = 0
      temNum2++
      var _res2 = res2.next()
      var res3 = db.tem.find({
        name: _res2.name
      });
      // print('模板名称:' + _res2.name + '该模板名文档数量:' + res3.count())
      while (res3.hasNext()) {
        var _res3 = res3.next()
        temNum3++
        temNum7++ 
        if (temNum7 % 500 === 0) {
          print('累计执行次数 temNum7:' + temNum7)
        }
        if (temNum3 % 50 === 0) {
          print('模板名称:' + _res2.name + '该模板名文档数量:' + res3.count())
          print('tem:' + temNum1 + ' - ' + temNum2 + ' - ' + temNum3)
        }
        try {
          if (
            (_res2._id.toString().slice(-5) !== _res3._id.toString().slice(-5))
          ) {
            temNum4++
            // print('有符合条件的重复的tem 删除较早的')
            if ((parseInt(_res2.create_time) > parseInt(_res3.create_time))) {
              try {
                db.tem.remove({
                  "name": _res3.name,
                  "create_time": _res3.create_time
                });
                
                
              } catch (e) {
                print(_res3.name + '-' + _res3._id)
              }
            } else {
              try {
                db.tem.remove({
                  "name": _res2.name,
                  "create_time": _res2.create_time
                });
                _res2 = _res3
              } catch (e) {
                print(_res3.name + '-' + _res3._id)
              }
            }
            if (temNum4 % 1000 === 0) {
              print('删除重复模板名' + _res3.name + '  删除重复数量 temNum4:' + temNum4)
            }
            
          } else {
            temNum6++
            if (temNum6 % 1000 === 0) {
              print('tem没有符合条件需要去重的模板 模板名:' + _res3.name + '   ' + '累计数量temNum6:' + temNum6)
            }
          }
        } catch (e) {
          temNum5++
          print(e)
          print('catch 数量:' + temNum5 + ' - ' + _res3.name + '-' + _res3._id)
        }

      }
    }

  // <!-- // 修改模版表模版时间格式为int -->
  var res = db.tem.find();

  while (res.hasNext()) {
    var re = res.next();
    try {
      db.tem.update({}, {
        $set: {
          "create_time": NumberInt(re.create_time)
        }
      }, true, true);
    } catch (e) {
      print('tem 出错')
      print(re._id)
    }

  }

  // <!-- // 模版迁移表 -->
  var res = db.tem.find();
  // num: 迁移的数量
  var num = 0;
  while (res.hasNext()) {
    var re = res.next();
    try {
      num++
      // insertOne 改 save  
      db.templates.save({
        _id: re._id,
        name: re.name,
        content: re.content,
        mark: re.mark,
        thumbnail: re.cdn,
        modifier: ObjectId("5fc9a06ebcb3cf72f271bc7a"),
        label: [],
        create_time: NumberInt(parseInt(re.create_time)),
        renew_time: NumberInt(parseInt(re.create_time)),
        config: re.config
      });
    } catch (e) {
      print('tem表 出错')
      print(re._id)
    }
    
  }
  print('迁移templates表 save文档数量:' + num)
  // 删除过渡表
  db.tem.drop()
}

// 用户表 users相关处理
var users = function () {
  // <!-- // 用户表迁移 -->
  var res = db.us.find();
  while (res.hasNext()) {
    var re = res.next();
    try {
      // 这里insertOne改为save 存在的话 就更新
      db.users.save({
        _id: re._id,
        account: re.account,
        password: re.password ? re.password : '',
        role: re.role,
        name: re.name,
        create_time: NumberInt(parseInt(re.create_time)),
        status: NumberInt(parseInt(re.status)),
        // status: re.status ? NumberInt(parseInt(re.status)) : NumberInt(1)
      });
    } catch (e) {
      print('users ')
      print(re._id)
    }

  }
  // 删除过渡表
  db.us.drop()
}

// 实验表 experiments相关处理
var experiments = function () {
  var res = db.exp.find();
  print('experiments文档数量:' + db.exp.find().count())
  var num=0; 
  while (res.hasNext()) {
    var re = res.next();
    try {
        // insert 暂时改为 save
        db.experiments.insert(re)
        num++
        if (num % 500 === 0) {
          print('db.experiments.save 数量 num:' + num)
        }
      
    } catch (e) {
      print('experiments re._id:')
      print(re._id)
      print(e)
    }

  }
  // 删除过渡表
  db.exp.drop()
}


// 素材表 sources
var sources = function () {
  var res = db.sour.find();
  var num = 0;
  print('sources文档数量:' + db.sour.find().count())
  while (res.hasNext()) {
    var re = res.next();
    db.sources.insert({
      _id: re._id,
      local_url: re.local_url,
      url: re.url,
      file_type: re.file_type,
      source_type: re.source_type, // source_type用不到 可以去掉
      classify: re.source_type,
      description: re.description,
      user: re.user,
      create_time: NumberInt(parseInt(re.create_time)),
      renew_time: NumberInt(parseInt(re.renew_time)),
      md5: re.md5 ? re.md5 : ''
    })
    num++;
    if (num % 100 === 0) {
      print('db.sources.insert() 数量:' + num)
    }
  }
  // 删除过渡表
  db.sour.drop()
}

// 组合指标表 combinations
var combinations = function () {
  var res = db.comb.find();
  while (res.hasNext()) {
    var re = res.next();
    var res2 = db.us.findOne({
      _id: re.user
    });
    if (res2) {
      var res3 = db.users.findOne({
        account: res2.account
      });
      try {
        db.combinations.insert({
          name: re.name,
          field: re.field,
          formula: re.formula,
          user: res3._id,
          comId: NumberInt(parseInt(re.comId))
        })
      } catch (e) {
        print('combinations')
        print(re._id)
      }

    }
  }
  // 删除过渡表
  db.comb.drop()
}

print('开始执行活动表 activities相关处理')
activities()
print('结束')


// 模板表 templates相关处理
print('开始 templates相关处理')
templates()
print('结束')

// 用户表 users相关处理
print('开始 users相关处理')
users()
print('结束')

// 实验表 experiments相关处理
print('开始 experiments相关处理')
experiments()
print('结束')

print('素材表 sources 开始 sources相关处理')
sources()
print('结束')

// 组合指标表 combinations
print('开始 combinations相关处理')
combinations()
print('结束')


print('活动发布历史表 activityhistories   还在测试 所以放最后')
activityhistories()
print('结束')
执行过程截图

命令行定义shell函数
命令行执行shell函数
在这里插入图片描述
在这里插入图片描述
这就完成了数据库迁移的动作了,结果如下
在这里插入图片描述


谢谢你阅读到了最后~
期待你关注、收藏、评论、点赞~
让我们一起 变得更强


推荐阅读
MongoDB中的多表关联查询、聚合管道($lookup、$unwind)
mongodb、mongoose相关
前端linux基础,这一篇就够了

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐