Sling Academy
Home/Python/PyMongo: How to create/drop databases

PyMongo: How to create/drop databases

Last updated: February 08, 2024

Introduction

PyMongo is a Python distribution containing tools for working with MongoDB, and is the recommended way to work with MongoDB from Python. This guide will demonstrate how to create and drop databases for both beginners and advanced users, enhanced with multiple code examples.

Getting Started

Before diving into creating or dropping databases, ensure you have MongoDB and PyMongo installed. You can install PyMongo with pip:

pip install pymongo

Once installed, import MongoClient to connect to your MongoDB server:

from pymongo import MongoClient
client = MongoClient('localhost', 27017)

Creating a Database

In MongoDB, databases are created automatically when you first store data in them. Herehow to explicitly create a database:

db = client['new_database']
print('Database created: ', db.name)

This code doesncreate a database in MongoDB immediately. Instead, the database is created as soon as it gets its first collection and document.

Creating Collections and Documents

To create a collection within your new database and add a document, you can use the following:

collection = db['new_collection']
document = {'key': 'value'}
collection.insert_one(document)
print('Collection and document created')

This action creates both the collection and the document, effectively creating the database.

Dropping a Database

To drop a database, you can use the drop_database method:

client.drop_database('new_database')
print(database name dropped!)

Be cautious with this command as it will permanently delete the specified database and its data.

Advanced Topics

Listing Databases

Before creating or dropping a database, it might be useful to list all databases:

databases = client.list_database_names()
print(Databases: ', ', '.join(databases))

Checking Database Existence

To check if a database exists, you can use:

db_list = client.list_database_names()
if 'target_database' in db_list:
    print('Database exists')

Working with Authentication

When working with secured databases that require authentication, you can connect to MongoDB like this:

client = MongoClient('mongodb://username:password@localhost:27017/')

Conclusion

Creating and dropping databases in MongoDB using PyMongo is straightforward once you grasp the basic concepts. By following the outlined steps, yousharpen your database management skills and better understand how databases in MongoDB are managed programmatically. Whether youe working on a small project or an enterprise-level application, these techniques are essential for effective database management.

Next Article: PyMongo: Find documents within a day/week/month/year

Previous Article: PyMongo: How to create/drop indexes

Series: Data Persistence in Python – Tutorials & Examples

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types