Can I create a new database simply by connecting to the MongoDB server, or is there another way to create it using Python? If so, how is this done?
from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] #Creating a collection collection = db['example'] print("Collection created........")
What is PyMongo? PyMongo is MongoDB's official native driver for Python. It's a library that lets you connect to a MongoDB database and query the data stored using the MongoDB Query API.
MongoDB creates databases and collections automatically for you if they don't exist already.
For using python library with MongoDB, check out this documentation.
Warning: the example is based on Pymongo 2.1. If you're using Pymongo 3.4, check this doc.
from pymongo import Connection connection = Connection() db = connection['test-database'] collection = db['test-collection']
So here you can use any name for database and collection.
This is Mongodb 3.4 Version:
from pymongo import MongoClient client = MongoClient() db = client.primer coll = db.dataset
neither the database nor the collection are created until you attempt to write a document.
Document: Python Driver (PyMongo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With