¿Cómo ejecutar comandos mongo a través de scripts de shell?


Quiero ejecutar comandos mongo en el script de shell.

Traté de seguir camino test.sh

#!/bin/sh

mongo myDbName

db.mycollection.findOne()

show collections

Cuando ejecute el script anterior ./test.sh

Luego se establece la conexión mongo pero los siguientes comandos no se ejecutan

Cómo ejecutar otros comandos a través de sh script [test.sh] ?

Por favor ayúdame

Author: Tim Cooper, 2011-01-29

19 answers

También puede evaluar un comando usando la bandera --eval, si se trata de un solo comando.

mongo --eval "printjson(db.serverStatus())"

Tenga en cuenta: si está utilizando operadores Mongo, comenzando con un signo$, querrá rodear el argumento eval entre comillas simples para evitar que el shell evalúe al operador como una variable de entorno:

mongo --eval 'db.test.update({"name":"foo"},{$set:{"this":"that"}});'

De lo contrario puede ver algo como esto:

mongo --eval "db.test.update({\"name\":\"foo\"},{$set:{\"this\":\"that\"}});"
> E QUERY    SyntaxError: Unexpected token :
 340
Author: theTuxRacer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-16 19:59:54

Ponga su script mongo en un archivo .js.

Luego ejecuta mongo < yourFile.js

Ex:

Demo.js / / el archivo tiene su script

use sample  //db name
show collections

Mantenga este archivo en "c:\db-scripts"

Luego, en el indicador cmd, vaya a "c:\db-scripts"

C:\db-scripts>mongo < demo.js

Esto ejecutará el código en mongo y mostrará la salida

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>
 260
Author: Matt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-28 06:45:44

Esto funciona para mí bajo Linux:

mongo < script.js
 90
Author: Antonin Brettsnajdr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-31 18:05:04

Pon esto en un archivo llamado test.js:

db.mycollection.findOne()
db.getCollectionNames().forEach(function(collection) {
  print(collection);
});

Luego ejecútalo con mongo myDbName test.js.

 50
Author: Theo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-29 18:36:47

Hay una página de documentación oficial sobre esto también.

Ejemplos de esa página incluyen:

mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"
 33
Author: thaddeusmt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-27 20:00:45

El script de shell a continuación también funcionó muy bien para mí... definite tuvo que usar la redirección que Antonin mencionó al principio... eso me dio la idea de probar el documento aquí.

function testMongoScript {
    mongo <<EOF
    use mydb
    db.leads.findOne()
    db.leads.find().count()
EOF
}
 24
Author: David H. Young,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-21 04:44:34

En mi configuración tengo que usar:

mongo --host="the.server.ip:port" databaseName theScript.js 
 18
Author: Ed Williams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-03 19:42:35

¿qué tal esto:

echo "db.mycollection.findOne()" | mongo myDbName
echo "show collections" | mongo myDbName
 12
Author: Mark Butler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-08 17:40:29

Como sugiere theTuxRacer, puede usar el comando eval, para aquellos que lo están perdiendo como yo, también puede agregar el nombre de su base de datos si no está tratando de preformar la operación en la base de datos predeterminada.

mongo <dbname> --eval "printjson(db.something.find())"
 12
Author: Matt Clark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-22 20:07:43

Utilizo la sintaxis "heredoc", que David Young menciona. Pero hay una trampa:

#!/usr/bin/sh

mongo <db> <<EOF
db.<collection>.find({
  fieldName: { $exists: true }
})
.forEach( printjson );
EOF

Lo anterior NO funcionará, porque la frase "exists exists" será vista por el shell y sustituida por el valor de la variable de entorno llamada "exists."Que, probablemente, no existe, por lo que después de la expansión de shell, se convierte en:

#!/usr/bin/sh

mongo <db> <<EOF
db.<collection>.find({
  fieldName: { : true }
})
.forEach( printjson );
EOF

Para que pase tienes dos opciones. Uno es feo, uno es bastante agradable. Primero, el feo: escapar de los signs signos:

#!/usr/bin/sh

mongo <db> <<EOF
db.<collection>.find({
  fieldName: { \$exists: true }
})
.forEach( printjson );
EOF

I no recomiendo esto, porque es fácil olvidarse de escapar.

La otra opción es escapar del EOF, así:

#!/usr/bin/sh

mongo <db> <<\EOF
db.<collection>.find({
  fieldName: { $exists: true }
})
.forEach( printjson );
EOF

Ahora, puede poner todos los signos de dólar que desee en su heredoc, y los signos de dólar se ignoran. El lado negativo: Eso no funciona si necesita poner parámetros/variables de shell en su script mongo.

Otra opción con la que puedes jugar es meterte con tu shebang. Por ejemplo,

#!/bin/env mongo
<some mongo stuff>

Hay varios problemas con esto solución:

  1. Solo funciona si está intentando hacer un script de shell de mongo ejecutable desde la línea de comandos. No puedes mezclar comandos de shell regulares con comandos de shell de mongo. Y todo lo que guarda al hacerlo es no tener que escribir "mongo" en la línea de comandos... (razón suficiente, por supuesto)

  2. Funciona exactamente como " mongo ", lo que significa que no le permite usar el comando" use ".

He intentado agregar el nombre de la base de datos para el shebang, que usted pensaría que funcionaría. Desafortunadamente, la forma en que el sistema procesa la línea shebang, todo después del primer espacio se pasa como un solo parámetro (como si se citara) al comando env, y env falla al encontrarlo y ejecutarlo.

En su lugar, debe incrustar el cambio de la base de datos dentro del propio script, de la siguiente manera:

#!/bin/env mongo
db = db.getSiblingDB('<db>');
<your script>

Como con cualquier cosa en la vida, " ¡hay más de una manera de hacerlo!"

 11
Author: John Arrowwood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-29 14:19:08

En caso de que tenga la autenticación habilitada:

mongo -u username -p password --authenticationDatabase auth_db_name < your_script.js
 8
Author: Moses Xu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-02 00:11:06

Gracias printf! En un entorno Linux, esta es una mejor manera de tener un solo archivo ejecutando el programa. Digamos que tienes dos archivos, mongoCmds.js con múltiples comandos:

use someDb
db.someColl.find()

Y luego el archivo de shell del controlador, runMongoCmds.sh

mongo < mongoCmds.js

En su lugar, tener un solo archivo, runMongoCmds.sh que contengan

printf "use someDb\ndb.someColl.find()" | mongo

El printf de Bash es mucho más robusto que echo y permite que el \n entre comandos los fuerce en múltiples líneas.

 7
Author: tgoneil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-17 21:27:57

Crear un archivo de script; escribir comandos:

#!/bin/sh
mongo < file.js

En file.js escriba su consulta mongo:

db.collection.find({"myValue":null}).count();
 7
Author: GSK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-21 16:37:30
mongo db_name --eval "db.user_info.find().forEach(function(o) {print(o._id);})"
 4
Author: Talespin_Kit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-06 15:30:29

Flag shell flag también se puede usar para archivos javascript

 mongo --shell /path/to/jsfile/test.js 
 3
Author: Jackson Harry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-30 12:57:41

Si quieres manejarlo con una línea es una manera fácil.

file.sh --> db.EXPECTED_COLLECTION.remove("_id":1234)

cat file.sh | mongo <EXPECTED_COLLECTION>
 2
Author: Erçin Akçay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-22 15:50:07
mongo <<EOF
use <db_name>
db.getCollection("<collection_name>").find({})
EOF
 1
Author: Erdem ÖZDEMİR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-27 07:38:00

En mi caso, puedo usar convenientemente \n como separador para el siguiente comando mongo que quiero ejecutar y luego canalizarlos a mongo

echo $'use your_db\ndb.yourCollection.find()' | mongo
 0
Author: Ardhi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 09:57:43

Recientemente migró de mongodb a Postgres. Así es como usé los guiones.

mongo < scripts.js > inserts.sql

Lee el scripts.js y redirige la salida a inserts.sql.

scripts.js se ve así

use myDb;
var string = "INSERT INTO table(a, b) VALUES";
db.getCollection('collectionName').find({}).forEach(function (object) {
    string += "('" + String(object.description) + "','" + object.name + "'),";
});
print(string.substring(0, string.length - 1), ";");

inserts.sql se ve así

INSERT INTO table(a, b) VALUES('abc', 'Alice'), ('def', 'Bob'), ('ghi', 'Claire');
 -1
Author: mythicalcoder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-07 07:30:24