mongo execute JavaScript scripts

mongo client has two ways to interact with mongodb service, one is the mongo shell, one is the implementation of javascript script .mongo shell, usually with more, but javascript script is rarely used. Some time ago, in a project js script by writing batch update some data, do some summary.

How to perform

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

Example: mongo localhost: 27017 / hr_assistant index.js in index.js the talk mongodb say hello, and then print what the current database

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

Results of the:

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. Above is to perform a js script directly through the mongo client, you can also use the load function enter the client command line interaction to load a script

Example:

// 进入客户端
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

Note that the above two methods need to pay attention to the script path problem, it is best to execute commands in script mongo all folders, worry, save trouble.

Different js script with the mongo Shell

mongoShell is a simplified version of the JavaScript Shell, you are free to write javascript code, but also built a lot of unique objects and methods belong mongodb, but you can not use a script like show databases, show collections, use test such an order is required the client provides functions such as db.getCollectionNames (); the following table is a function corresponding to the common commands

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

There are two commonly used in the function js script, print () / printjson () parameter may be printed to standard output.

Example 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}`);

operation result:

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

Happy playing

Learn the difference between js scripts and how to run and mongoshell, it can become a curdBoy the js file, because you can use all CRUD method mongo provided by the client in the js file js plus built-in object / array method It is simply more powerful.
Here is a simple example

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}`);

operation 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 })

Guess you like

Origin www.cnblogs.com/pandapeter/p/11294232.html