Creating MongoDB Collections with Python

At some point in your MongoDB journey, you will need to create collections to store data. In this article, we will show you how to create a MongoDB collection with Python.

Prerequisites

Before we start, ensure that you have the following:

  • Python installed on your computer
  • Pymongo package installed
  • MongoDB Atlas cluster or a local MongoDB server running on your machine

Connecting to MongoDB

To start, you need to connect to your MongoDB instance. You can connect to MongoDB using the Pymongo package by providing the MongoDB connection string.

import pymongo

# replace the uri string with your MongoDB deployment's connection string
client = pymongo.MongoClient("<connection-string>")

db = client.test_database

Creating a Collection

Now that you have connected to your MongoDB instance, you can create a new collection in your MongoDB database using the create_collection() method.

# create a new collection called "customers"
collection = db.create_collection("customers")

You can also create a collection by inserting a document into it. If the collection does not exist, MongoDB will create it for you.

# insert a document into a new collection called "products"
collection = db.products
collection.insert_one({"name": "product 1", "price": 10.99})

Listing Collections

To list all collections in your database, you can use the list_collection_names() method.

# list all collections in the database
print(db.list_collection_names())

Conclusion

In this article, we have shown you how to create a MongoDB collection using Python. We hope this guide was helpful to you. If you have any questions, please leave a comment below.

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?