I am using a dockerfile and bash script
It should be noted that the mongo db is already running and I can interactively connect to it so this is not an issue.
Dockerfile
FROM mongo
WORKDIR /root
ENV PATH /root/bin:$PATH
WORKDIR /root/bin
COPY import_files/latest.csv .
COPY import_files/field_file_types.txt .
COPY scripts/import.sh .
RUN chmod x import.sh
CMD sh /root/bin/import.sh
import.sh
#!/bin/bash
ENV_HOST="mongo1"
ENV_USER="user"
ENV_PASS="pass"
ENV_DB="mydb"
ENV_TABLE="mycollection"
# mongoimport -h "${ENV_HOST}:27017" -u "${ENV_USER}" -p "${ENV_PASS}" -c $ENV_TABLE --authenticationDatabase ${ENV_DB} --type csv --file ./latest.csv --columnsHaveTypes --fieldFile=./field_file_types.txt
mongoimport --uri "mongodb://${ENV_USER}:${ENV_PASS}@${ENV_HOST}/${ENV_DB}" -c $ENV_TABLE --type csv --file ./latest.csv --columnsHaveTypes --fieldFile=./field_file_types.txt
exit 0
This is my mongo import statement
mongoimport
-h "mongo1:27017"
-u "user"
-p "pass"
-c "mycollection"
--authenticationDatabase "mydb"
--type csv
--file ./latest.csv
--columnsHaveTypes
--fieldFile=./field_file_types.txt
Which in my console outputs like this:
mongodb://user:pass@mongo1:27017/admin mydb mycollection
And I get error:
error parsing command line options: Invalid Options: Cannot specify different username in connection URI and command-line option ("user" was specified in the URI and "mycollection" was specified in the --username option)
I have also tried it as a uri:
mongoimport --uri "mongodb://user:pass@mongo1/mydb" -c mycollection --type csv --file ./latest.csv --columnsHaveTypes --fieldFile=./field_file_types.txt
Which in my console looks like this:
Mongo import csv = mongodb://user:pass@mongo1:27017/admin mydb mycollection
Enter password:
Why is it asking for password? I provided it as above? Also its exactly the same output as the previous example.
CodePudding user response:
It turns out when I was running docker-compose, I had a script which granted me permission to all databases: (but only if I login as an admin)
mongo <<EOF
use admin
db.createUser(
{
user: "${MONGO_USER}",
pwd: "${MONGO_PASS}",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
use ${MONGO_DB}
db.createCollection("${MONGO_COLLECTION}")
EOF
This means when I connect to mongo I must connect via 'admin' in order to access the other databases. To access the database in question I can include it in the uri string but I must also add -
--authenticationDatabase admin
import script example:
mongoimport --uri "mongodb://user:passt@mongo1/db" -c todos --type csv --file /data/db/latest.csv --columnsHaveTypes --fields "id.auto(),todoText.string(),created_timestamp.date(2006-01-02 15:04:05),completed.date(2006-01-02 15:04:05)" --authenticationDatabase admin