databasemongodbshellcommand-linemongodb-java

mongodb script file


I am newbie to mongodb.

We can execute list of queries by specifying it in a script .sql file in relational db and can run it by running the command source c:\test.sql.

For instance

CREATE DATABASE `s

    andbox`;
    USE `sandbox`;
    
    CREATE TABLE pet (
        name VARCHAR(20), 
        owner VARCHAR(20),
        species VARCHAR(20), 
        sex CHAR(1), 
        birth DATE, 
       death DATE
    );
    SHOW TABLES;
    ```
    
    Then it can be execute as 
    
    ```
    $ mysql -u root -p admin
    mysql > source test.sql;
    ```
    
    
    ### Questions
    
    - How can we do that in mongodb?
    - Which type of file can we store `mongodb` commands?
    - How can we execute a `mongodb` script?
    
    
    #!/bin/bash
    
    # Load domain file
    DOMAIN_FILE="NONPCFPROD/domain-prod.txt"
    declare -A DOMAIN_MAP
    
    # Read and map domain -> cpcode
    while IFS= read -r line; do
      [[ -z "$line" ]] && continue
      IFS=':' read -ra parts <<< "$line"
      if [ "${#parts[@]}" -ge 3 ]; then
        domain=$(echo "${parts[1]}" | xargs)
        cpcode=$(echo "${parts[2]}" | xargs)
        DOMAIN_MAP["$domain"]="$cpcode"
      fi
    done < "$DOMAIN_FILE"
    
    # Input domains (example: passed via environment variable or parameter)
    DOMAIN_INPUT="${DOMAIN_INPUT:-example.com,anotherdomain.com}"  # Replace with actual input source
    IFS=',' read -ra DOMAIN_LIST <<< "$DOMAIN_INPUT"
    
    # Collect cpCodes for selected domains
    CPCODE_LIST=()
    for domain in "${DOMAIN_LIST[@]}"; do
      trimmed_domain=$(echo "$domain" | xargs)
      cpcode="${DOMAIN_MAP[$trimmed_domain]}"
      if [ -n "$cpcode" ]; then
        CPCODE_LIST+=("$cpcode")
      fi
    done
    
    # Iterate over cpcode/domain pairs
    for ((i = 0; i < ${#CPCODE_LIST[@]}; i++)); do
      strInputCpCode="${CPCODE_LIST[$i]}"
      strInputDomain="${DOMAIN_LIST[$i]}"
    
      if [ -n "$strInputCpCode" ] && [ -n "$strInputDomain" ]; then
        echo "Following domain will be purged: $strInputDomain"
        export HTTPS_PROXY="vzsrvproxy.app.syfbank.com"
        # Example purge command (replace below)
        # curl -X POST -H "Content-Type: application/json" -d "{\"cpcode\": \"$strInputCpCode\", \"domain\": \"$strInputDomain\"}" <YOUR_PURGE_ENDPOINT>
      fi
    done


Solution

  • You can do it with shell script. You can execute the commands using the following command.

    ./mongo server:27017/dbname --quiet my_commands.js
    

    For details check Scripting the shell document in Mongo docs.