-1

I have set up `mongo' DB on my machine using the following docker-compose file.

version: "3.1"
services:
  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    volumes:
      - ${PWD}/data:/usr/src/data

Now, I want to insert sample data into a collection named books using the below command

mongo books < booksJson.js

But when I execute this command I am getting the following error

MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/books?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("57936227-aa22-4d5f-841b-59788847bc3c") }
MongoDB server version: 4.4.1
WriteCommandError({
        "ok" : 0,
        "errmsg" : "command insert requires authentication",
        "code" : 13,
        "codeName" : "Unauthorized"
})
bye

Below are the contents of my booksJson.js file.

db.books.insert([
{
     title: 'xyz',
     test: 1
}
])

Any pointers towards how to use mongo.exe to import JSON data using a JavaScript file and redirection operator?

3
  • I think you have to tell mongo which database you want to insert and add credentials for that db. for example: mongo --db library -u username -p password books < booksJson.js Commented Oct 3, 2020 at 7:44
  • 1
    See this post for: How to load multiple js files using mongo shell. Commented Oct 3, 2020 at 10:17
  • @Mahan it looks like --db option is not valid. getting error : Error parsing command line: unrecognised option '--db' Commented Oct 4, 2020 at 2:06

1 Answer 1

1

@Prasad's comment/pointer helped to find out the solution.

I was able to import data using the following command.

mongo localhost:27017/bookdb  --authenticationDatabase "admin" -u root -p example  < booksJson.js

I have to mention authinticationDatabase flag in order to get it to work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.