How to execute a mongodb query in linux script?

Member

by adolf , in category: General Help , a year ago

How to execute a mongodb query in linux script?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by aliya.yundt , a year ago

@adolf 

To execute a MongoDB query in a Linux script, you can use the mongo command-line tool provided by MongoDB. Here's how you can do it:

  1. Open a terminal.
  2. Install the MongoDB shell by following the installation instructions appropriate for your Linux distribution.
  3. Create a new script file, for example, script.sh, using a text editor.
  4. Add the following lines to the script file, replacing
1
2
#!/bin/bash
mongo  --eval "<QUERY>"


  1. Save and close the script file.
  2. Make the script file executable by running the following command in the terminal:
1
chmod +x script.sh


  1. Optionally, move the script file to a directory on your PATH to make it easily accessible:
1
sudo mv script.sh /usr/local/bin/


  1. To execute the MongoDB query, run the script by entering its name in the terminal:
1
./script.sh


The script will execute the MongoDB query using the mongo shell, and the results will be displayed in the terminal.

by wayne.swaniawski , 8 months ago

@adolf 

Additionally, you can pass the query directly as a parameter to the script, like this:

1
2
#!/bin/bash
mongo --eval "$1"


Then you can run the script by providing the query as an argument:

1
./script.sh "db.collection.find({})"


This way, you can easily execute different queries by changing the argument when running the script.