Mongodb Create Db in Python
Creating a Database in MongoDB Using Python
In MongoDB, databases are created automatically when you first store data in them. You don't explicitly create a database like you would in a relational database. Instead, when you insert a document into a collection, MongoDB creates the database and collection if they do not already exist.
To create a database in MongoDB using Python, you can follow these steps:
Steps to Create a Database in MongoDB
Install the
pymongopackage (if you haven’t already):pip install pymongoConnect to MongoDB using
pymongo.Create or select the database by simply assigning a database name.
Create a collection within that database by inserting data into it.
Example: Creating a Database and Collection in MongoDB
import pymongo# Create a MongoClient object to connect to MongoDBclient = pymongo.MongoClient("mongodb://localhost:27017/")# Create (or select) a databasedb = client["my_new_database"]# Create (or select) a collection within the databasecollection = db["my_new_collection"]# Insert a document into the collectiondocument = {"name": "Alice", "age": 25, "city": "New York"}collection.insert_one(document)# Verify that the data was inserted by querying the collectionresult = collection.find_one({"name": "Alice"})print(result)# Close the connection when doneclient.close()Explanation of the Code:
MongoClient: Establishes a connection to the MongoDB server.client["my_new_database"]: Selects (or creates if it doesn’t exist) the databasemy_new_database.db["my_new_collection"]: Selects (or creates if it doesn’t exist) the collectionmy_new_collection.insert_one(document): Inserts a single document into the collection.
Creating a Database and Collection
If the database
my_new_databasedoesn’t exist, MongoDB will create it when you insert a document into a collection.Similarly, if the collection
my_new_collectiondoesn’t exist, MongoDB will create it when you insert the document.
Verifying Database Creation
You can check if the database was created by listing all databases:
# List all databasesprint(client.list_database_names())You can also list the collections in the newly created database:
# List all collections in the databaseprint(db.list_collection_names())Note on Database Creation
MongoDB doesn’t actually create a database until you have stored at least one document in it. Until that time, the database won't appear in the list of databases.
Similarly, collections are created the moment you insert data into them.
Conclusion
In MongoDB, databases and collections are created automatically when you insert data.
There is no explicit
create databaseorcreate collectioncommand like in SQL databases.MongoDB uses a flexible schema, so you can add documents to collections with different structures easily.
This process simplifies the creation of new databases and collections while still giving you complete control over your data.