PyMongo - Create database with no collections or documents

Hello,

I’m creating some functions with Python using PyMongo, create database and create collection. I’ve read the docs and it says that in order to databases to be created (committed) a document must be written.

Is there a way to only create a database without having collections and documents? Or is there a way to handle this kind of situation?

Short answer no… MongoDB doesn’t provide any command to create “database”

if you drop all collections in a database, you delete the database too.

you may try yourself;

List all databases.

show dbs

switch the database you want to create (non-exists database name will work)

use new_database;

Insert an empty document into the collection you want to create (again, non-exists collection name will work)

db.new_collection.insertOne({});

drop the collection, you just created and inserted a document.

db.new_collection.drop();

List all databases, again.

show dbs

Why do you want/need to create an empty database? It doesn’t feel very MongoDB-ish…

I arrived here with same question :grimacing:.
It’s first time for me with Mongo, and I have the mental model from SQL.

My test case is a CMS (payload) that need a MongoDB instance in order to persist data.
Payload will create and fill “collections”. I do not even know collections names.

Typical connection string for payload are - in local env - mongodb://localhost:27017/payload-db
Here payload-db is the name of the database.

But when i launch a MongoDb instance locally, there is no “payload-db” database.
There are admin, config, local.

At this point, for me , the natural things to do is the mongo’s equivalent of SQL’s CREATE DATABASE payload-db