Python – MongoDB – Create Collection

Python - MongoDB - Create Collection

MongoDB is one of the most popular NoSQL databases. It is free and open-source cross-platform database. In this article, we will learn how to create a collection in MongoDB using Python.

Prerequisites

  1. Python installed on your system.
  2. pymongo module for python. You can install it using pip. Use the following command to install.
pip install pymongo

Step 1 – Importing Required Libraries

To use MongoDB in Python, we need to import the pymongo module.

import pymongo

Step 2 – Creating a Connection

After importing the “pymongo” module, we are ready to create a connection with the MongoDB server. We connect to the default “localhost” interface on port “27017”.

# Creating connection object
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Prints all available databases
print(client.list_database_names())

Step 3 – Creating a Collection

We use the “create_collection()” method to create a collection in MongoDB. Here is an example:

# Creating a collection
mydb = client["mydatabase"]
mycol = mydb["customers"]

Step 4 – Inserting Documents

We use the “insert_one()” method to insert documents into a collection.

# Inserting a document
mycol.insert_one({ "name": "John", "address": "Highway 37" })

Step 5 – Retrieving Documents

We use the “find()” method to retrieve documents from a collection.

# Retrieving a document
for x in mycol.find():
  print(x)

The output of the above code will look like this:

{'_id': ObjectId('60ae3f8bf86d959411270427'), 'name': 'John', 'address': 'Highway 37'}

Step 6 – Dropping a Collection

We use the “drop()” method to drop a collection in MongoDB.

# Dropping a collection
mycol.drop()

Complete Example

Here is the complete example:

import pymongo

# Creating connection object
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Prints all available databases
print(client.list_database_names())

# Creating a collection
mydb = client["mydatabase"]
mycol = mydb["customers"]

# Inserting a document
mycol.insert_one({ "name": "John", "address": "Highway 37" })

# Retrieving a document
for x in mycol.find():
  print(x)

# Dropping a collection
mycol.drop()

The output of the above code will look like this:

['admin', 'config', 'local']
{'_id': ObjectId('60ae3f8bf86d959411270427'), 'name': 'John', 'address': 'Highway 37'}

Conclusion

In this tutorial, we learned how to create a collection in MongoDB using Python. We also learned how to insert and retrieve documents from a collection.

Leave a Reply

Your email address will not be published. Required fields are marked *