mongo执行JavaScript脚本

Posted pandapeter

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mongo执行JavaScript脚本相关的知识,希望对你有一定的参考价值。

mongo客户端有两种方式与mongodb服务进行交互,一种是mongo shell,一种是执行javascript脚本.mongo shell,平时用的比较多,但是javascript脚本却很少用.前段时间,在一个项目中通过写js脚本批量的更新了一些数据,做一下总结.

如何执行

  1. mongo host:port/database /dir/xxxx.js

示例: mongo localhost:27017/hr_assistant index.js 在index.js中先跟mongodb打个招呼,然后打印一下当前的数据库

print('hello mongodb')
// 打印连接之后的数据库
print(db);

执行结果:

MongoDB shell version v4.0.11
connecting to: mongodb://localhost:27017/hr_assistant?gssapiServiceName=mongodb
Implicit session: session  "id" : UUID("3e0c8e42-57d5-429d-a00d-bad97ec95d73") 
MongoDB server version: 4.0.11
hello mongodb
hr_assistant
  1. 上述方式是通过mongo客户端直接执行一个js脚本,也可以在进入客户端的命令行交互中使用load函数去加载一个脚本

实例:

// 进入客户端
pan@ubuntu18:~/disk/panyanan/blog/mongodb$ mongo localhost:27017/hr_assistant
MongoDB shell version v4.0.11
connecting to: mongodb://127.0.0.1:27017/
// load脚本文件
> load('index.js')
hello mongodb
hr_assistant
true

注意上述两种方式都需要注意脚本的路径问题,最好是在脚本所有文件夹去执行mongo命令,省心,省事.

js脚本与mongo Shell 的不同

mongoShell是一个简化版的JavaScript Shell, 可以自由的编写javascript代码,也内置了很多属于mongodb的特有对象及方法,但是在脚本中你无法使用像 show databases、show collections、use test这种命令,需要使用客户端提供函数如db.getCollectionNames();下面这个表格是常用命令对应的函数

commands function
show dbs, show databases db.adminCommand(‘listDatabases‘)
use db db = db.getSiblingDB(‘db‘)
show collections db.getCollectionsNames()
show users db.getUsers()

还有两个在js脚本中常用的函数,print()/printjson()可以将参数打印到标准输出上。

示例 index.js:

//  因为是--nodb 形式启动的mongo客户端 所以新建一个连接
const conn = new Mongo('localhost:27017');
print(`连接: $conn`)
let db = conn.getDB('hr_assistant');
print(`当前数据库:$db`);
const dbs = db.adminCommand('listDatabases');
print('显示所有的数据库:')
printjson(dbs);
const collections = db.getCollectionNames();
print(`$db中的collections:`);
printjson(collections);
db = db.getSiblingDB('test');
print(`切换数据库为$db`);

运行结果:

pan@ubuntu18:~/disk/panyanan/blog/mongodb$ mongo --nodb index.js
MongoDB shell version v4.0.11
连接: connection to localhost:27017
当前数据库:hr_assistant
显示所有的数据库:

        "databases" : [
                
                        "name" : "admin",
                        "sizeOnDisk" : 32768,
                        "empty" : false
                ,
                
                        "name" : "config",
                        "sizeOnDisk" : 49152,
                        "empty" : false
                ,
                
                        "name" : "hr_assistant",
                        "sizeOnDisk" : 98873344,
                        "empty" : false
                ,
                
                        "name" : "local",
                        "sizeOnDisk" : 73728,
                        "empty" : false
                
        ],
        "totalSize" : 99028992,
        "ok" : 1

hr_assistant中的collections:
[
        "hr_business_call_records",
        "hr_business_info_collection",
        "hr_business_info_follow",
        "hr_business_info_interviewed",
        "hr_business_info_meeting",
        "hr_business_info_planned",
        "hr_business_info_user",
        "hr_business_resume_assessment",
        "hr_business_resume_basic_work",
        "hr_business_resume_basiceducation",
        "hr_business_resume_basichealth",
        "hr_business_resume_basicinfo",
        "hr_business_resume_head_portrait",
        "hr_business_resume_jobobjective",
        "hr_business_resume_percentage",
        "hr_business_resume_workexp",
        "hr_business_sign_list",
        "hr_business_signed_result"
]
切换数据库为test

愉快的玩耍

了解了如何运行js脚本以及与mongoshell的区别,就可以在js文件中成为一个curdBoy了.因为在js文件中可以使用mongo客户端提供的所有增删改查方法,加上js内置对象/数组的方法,简直是如虎添翼.
下面是个简单的示例

const conn = new Mongo('localhost:27017');
const db = conn.getDB('test');
// 向emp集合中插入一些记录
let emps =[
  
    ename: 'Smith',
    deptno: 20,
    job: 'salesman',
    mgr: '',
    sal: 800,
  ,
  
    ename: 'Peter',
    deptno: 30,
    job: 'manager',
    mgr: '',
    sal: 1000,
  ,
  
    ename: 'Jack',
    deptno: 40,
    job: 'president',
    mgr: '',
    sal: 3000,
  ,
  
    ename: 'Rose',
    deptno: 50,
    job: 'analyst',
    mgr: '',
    sal: 1500,
  ,
] 
// 批量插入
let result = db.emps.insert(emps);
print(`批量插入一写员工`)
print(result);
// 获取jack
let jack = db.emps.findOne(ename: 'Jack');
print(`获取jack:`)
printjson(jack)
// 调整jack的薪资为5000
result = db.emps.update(_id: jack._id, $set: sal: 5000)
jack = db.emps.findOne(ename: 'Jack');
// 更新薪资后的jack
print('更新薪资后的jack:')
printjson(jack)
// 获取所有的员工
emps = db.emps.find();
print('获取所有的员工:');
// 更新所有员工的领导为jordan
emps.forEach(function(emp) 
  printjson(emp);
  emp.mgr = 'Jordan';
  db.emps.save(emp)
);

emps = db.emps.find();
print('更新所有员工的领导为jordan');
while(emps.hasNext()) 
  printjson(emps.next())

result = db.emps.remove(); 
print(`删除员工:: $result`);

运行结果

pan@ubuntu18:~/disk/panyanan/blog/mongodb$ mongo --nodb curd.js
MongoDB shell version v4.0.11
批量插入一写员工
BulkWriteResult(
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 4,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
)
获取jack:

        "_id" : ObjectId("5d44fdd70998b36ed6983e6c"),
        "ename" : "Jack",
        "deptno" : 40,
        "job" : "president",
        "mgr" : "",
        "sal" : 3000

更新薪资后的jack:

        "_id" : ObjectId("5d44fdd70998b36ed6983e6c"),
        "ename" : "Jack",
        "deptno" : 40,
        "job" : "president",
        "mgr" : "",
        "sal" : 5000

获取所有的员工:

        "_id" : ObjectId("5d44fdd70998b36ed6983e6a"),
        "ename" : "Smith",
        "deptno" : 20,
        "job" : "salesman",
        "mgr" : "",
        "sal" : 800


        "_id" : ObjectId("5d44fdd70998b36ed6983e6b"),
        "ename" : "Peter",
        "deptno" : 30,
        "job" : "manager",
        "mgr" : "",
        "sal" : 1000


        "_id" : ObjectId("5d44fdd70998b36ed6983e6c"),
        "ename" : "Jack",
        "deptno" : 40,
        "job" : "president",
        "mgr" : "",
        "sal" : 5000


        "_id" : ObjectId("5d44fdd70998b36ed6983e6d"),
        "ename" : "Rose",
        "deptno" : 50,
        "job" : "analyst",
        "mgr" : "",
        "sal" : 1500

更新所有员工的领导为jordan

        "_id" : ObjectId("5d44fdd70998b36ed6983e6a"),
        "ename" : "Smith",
        "deptno" : 20,
        "job" : "salesman",
        "mgr" : "Jordan",
        "sal" : 800


        "_id" : ObjectId("5d44fdd70998b36ed6983e6b"),
        "ename" : "Peter",
        "deptno" : 30,
        "job" : "manager",
        "mgr" : "Jordan",
        "sal" : 1000


        "_id" : ObjectId("5d44fdd70998b36ed6983e6c"),
        "ename" : "Jack",
        "deptno" : 40,
        "job" : "president",
        "mgr" : "Jordan",
        "sal" : 5000


        "_id" : ObjectId("5d44fdd70998b36ed6983e6d"),
        "ename" : "Rose",
        "deptno" : 50,
        "job" : "analyst",
        "mgr" : "Jordan",
        "sal" : 1500

删除员工:: WriteResult( "nRemoved" : 4 )

以上是关于mongo执行JavaScript脚本的主要内容,如果未能解决你的问题,请参考以下文章

js基础

加载模块脚本失败:服务器以非 JavaScript MIME 类型“”响应。执行严格的 MIME 类型检查

想要阻止MongoDB或JavaScript脚本执行

前端笔记 (3.JavaScript 1)

加载模块脚本失败:服务器以“text/plain”的非 JavaScript MIME 类型响应

mongo在shell命令行直接执行js脚本