我想在shell脚本中执行mongo命令,例如在脚本test.sh中:
#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections
当我通过./test.sh执行这个脚本时,会建立到MongoDB的连接,但不会执行以下命令。
如何通过shell脚本test.sh执行其他命令?
我想在shell脚本中执行mongo命令,例如在脚本test.sh中:
#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections
当我通过./test.sh执行这个脚本时,会建立到MongoDB的连接,但不会执行以下命令。
如何通过shell脚本test.sh执行其他命令?
当前回答
关于这一点也有一个官方文档页面。
该页面的例子包括:
mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"
其他回答
关于这一点也有一个官方文档页面。
该页面的例子包括:
mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"
单shell脚本解决方案,能够传递mongo参数(——quiet, dbname,等):
#!/usr/bin/env -S mongo --quiet localhost:27017/test
cur = db.myCollection.find({});
while(cur.hasNext()) {
printjson(cur.next());
}
-S标志可能不适用于所有平台。
在我的设置中,我必须使用:
mongo --host="the.server.ip:port" databaseName theScript.js
mongodb的更新版本
mongosh --host="the.server.ip:port" databaseName theScript.js
mongo db_name --eval "db.user_info.find().forEach(function(o) {print(o._id);})"
将mongo脚本放到.js文件中。
然后执行mongo < yourFile.js
Ex:
Demo.js //file有你的脚本
use sample //db name
show collections
将此文件保存在“c:\db-scripts”中
然后在cmd提示符中转到"c:\db-scripts"
C:\db-scripts>mongo < demo.js
这将在mongo中执行代码并显示输出
C:\db-scripts>mongo < demo.js
Mongo shell version: 3.0.4
Connecting to: test
switched to db sample
users //collection name
tasks //collection name
bye
C:\db-scripts>