关于linux:Linux在shell脚本中执行MongoDB命令

6次阅读

共计 1856 个字符,预计需要花费 5 分钟才能阅读完成。

形式一 间接在 shell 中嵌入 MongoDB 命令

应用/usr/bin/mongo <<EOF mongodb 命令 EOF

  • EOF 是End Of File 的意思,只是一个标记,也能够替换为其余字符串
  • <<示意规范输出重定向
  • 两者配合,就是将一对 EOF 标记中的内容作为规范输出传递给程序
  • 在配合上 mongo 命令,就是将内容传递给 mongo,这样间接写 MongoDB 的命令就行
# create super DBA dba_root and DBA of pxjz dbz_pxjz
/usr/bin/mongo <<MongoDB
use admin;
isRootExist = (!!db.system.users.findOne({user:'dba_root'}));
isPxjzExist = (!!db.system.users.findOne({user:'dba_pxjz'}));
!isRootExist ? db.createUser({
    user: 'dba_root',
    pwd: '123',
    customData: {desc: '超级管理员'},
    roles: ['root']
}) : '超级管理员曾经存在';

use pxjz;
!isPxjzExist ? db.createUser({
    user: 'dba_pxjz',
    pwd: '123',
    customData: {desc: 'pxjz 数据库管理员'},
    roles: [{role: 'readWrite', db: 'pxjz'},
        {role: 'dbAdmin', db: 'pxjz'},
        {role: 'userAdmin', db: 'pxjz'}
    ]
}) : 'pxjz 数据库管理员曾经存在';

执行后果

形式二 编写独自的 mongo 脚本

独自创立一个 js 脚本,在其中输出要执行的 mongo 命令,而后执行该脚本

  • 编写脚本而后应用 mongo xxx.js 执行该脚本
  • 须要留神的是,mongo 脚本和个别的 js 文件还有些区别,用官网的话说就是,不能在 JavaScript 文件中应用任何 shell 帮忙程序(例如,应用 <dbname>,show dbs 等),因为它们不是无效的 JavaScript,但有替换的办法,参见下表
Shell 帮忙 等价 JavaScript
show dbs, show databases db.adminCommand(‘listDatabases’)
use <db> db = db.getSiblingDB(‘<db>’)
show collections db.getCollectionNames()
show users db.getUsers()
show roles db.getRoles({showBuiltinRoles: true})
show log<logname> db.adminCommand({‘getLog’ : ‘<logname>’})
show logs db.adminCommand({‘getLog’ : ‘*’})
it cursor = db.collection.find() if ( cursor.hasNext() ){cursor.next(); }

所以在编写脚本的时候,如果用到左侧列出的 Shell 帮忙,记得替换为右侧列对应的 JS

// create super DBA 'dba_root' and DBA of pxjz 'dbz_pxjz'
db = db.getSiblingDB('admin');
isRootExist = (!!db.system.users.findOne({user:'dba_root'}));
isPxjzExist = (!!db.system.users.findOne({user:'dba_pxjz'}));
// create super DBA
!isRootExist ? db.createUser({
    user: 'dba_root',
    pwd: '123',
    customData: {desc: '超级管理员'},
    roles: ['root']
}) : '超级管理员曾经存在';
// create DBA of pxjz
db = db.getSiblingDB('pxjz');
!isPxjzExist ? db.createUser({
    user: 'dba_pxjz',
    pwd: '123',
    customData: {desc: 'pxjz 数据库管理员'},
    roles: [{role: 'readWrite', db: 'pxjz'},
      {role: 'dbAdmin', db: 'pxjz'},
      {role: 'userAdmin', db: 'pxjz'}
    ]
}) : 'pxjz 数据管理员曾经存在';

执行后果

正文完
 0