In MongoDB, Collections are created implicitly when we insert documents into them.
To create a collection in MongoDB using "pymongo" library, which provides tools to interact with MongoDB databases.
However, we can also explicitly create collections using Python and the "pymongo" library.
Here's how we can create a collection in MongoDB using Python:
pip install pymongo
After importing "pymongo", we must provide a connection URL and database name to MongoClient.
# import pymongo library import pymongo # Connection URL and database name uri = "mongodb://localhost:27017/" database_name = "your_database_name" collection_name = "your_collection_name" # Connect to MongoDB server client = pymongo.MongoClient(uri) # Access or create the database selectedDB = client[database_name] # Access or create the collection collection = selectedDB[collection_name]
Replace "mongodb://localhost:27017/" with the connection string for your MongoDB server.
Replace "your_database_name" with the name of the database where you want to create the collection.
Replace "your_collection_name" with the name of the collection you want to create.
The "list_collection_names()" method is used to get a list of all collection names in the specified database.
If the specified collection name exists, it prints a message indicating that the collection already exists. Otherwise, it prints a message indicating that the collection does not exist.
Finally, it accesses or creates the specified collection using the "selectedDB[collection_name]" syntax.
To Check if the collection exists from mongoClient using `selectedDB.list_collection_names()` method.
if collection_name in selectedDB.list_collection_names(): print(f"The collection '{collection_name}' already exists.") else: print(f"The collection '{collection_name}' does not exist.")
Insert a document into specific 'collection' using the insert_one() method.
document = {'name': 'Alice', 'age': 33} collection.insert_one(document) print("Collection created and document inserted successfully.")
# show databases will list all databases show dbs; # check for collections within databases show collections