Explicit mongo database name in Docker app

Hi, I am a newbie to both mongo (and Docker too), so please bear with me :wink:

Started a REST api example project express/mongo/mongoose/typescript.
The API works fine, does what it is supposed to do, persists data, all nice and dandy, except - all the collections it creates are placed into the implicit database named test. Even if this database were to be the only one in the container, I would like to have more control and be more explicit about the db name I am using.

Below is my docker-compose.yml

version: '3.9'
    build: .
    container_name: api-mongodb
    restart: unless-stopped
      - DB_URL=mongodb://myself:pass123@mongo:27017
      - '3131:3131'
      - mongo
    container_name: mongo_container
    image: mongo:latest
    restart: always
      - mongo_dbv:/data/db/
  mongo_dbv: {}

I connect via mongoose.connect(process.env.DB_URL).

To be honest, I don’t see the effect of MONGO_INITDB_DATABASE anywhere.
When I cli into the container via

docker exec -it mongo_container mongosh -u myself -p pass123

and then show dbs, I don’t see a database named api anywhere. Tried appending api to the DB_URL string - this resulted in auth error.

So how can I force mongo into creating the database called api?
(Let me know if I can provide more info).


One year later and now I’m in the same situation. Did you find any solution by now?

Hi @Rafael_Jordao welcome to the community!

Are you in the exact same situation where you would like to use a database other than test?

If you’re using the mongosh shell, you can switch database with use <new_database_name>

If you’re using a driver, there are documentations on how to do this for each driver. For example in the node driver findOne page:

import { MongoClient } from "mongodb";

const client = new MongoClient(uri);
async function run() {
  try {
    const database = client.db("sample_mflix");
    const movies = database.collection("movies");

This will use the database called sample_mflix and put it in the database variable, and collection called movies in the movies variable.

There will be similar constructs in other drivers. Please consult the relevant example in your driver’s documentation (e.g. findOne) and you should be able to see similar examples to the above.

If this is not what you’re after, please open a new thread detailing what you need and any relevant background information (MongoDB versions, what you have tried, what’s the goal, etc.)

Best regards

Actually the MONGO_INITDB_DATABASE is working fine for me.

When I use mongosh I’m specifying its value.