Python MongoDB Datenbank erstellen
- Previous Page MongoDB Introduction
- Next Page MongoDB Create Collection
Datenbank erstellen
Um eine Datenbank in MongoDB zu erstellen, müssen Sie zunächst ein MongoClient-Objekt erstellen und die Verbindung URL mit der richtigen IP-Adresse und dem Namen der zu erstellenden Datenbank angeben.
Falls die Datenbank nicht existiert, erstellt MongoDB die Datenbank und stellt die Verbindung her.
Example
Datenbank "mydatabase" erstellen:
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"]
Important Note:A database in MongoDB will not be created before it receives content!
Before actually creating a database (and collection) in MongoDB, MongoDB will keep waiting for you to create at least one collection (table) with a document (record).
Check if the database exists
Remember: In MongoDB, a database will not be created before it receives content, so if this is your first time creating a database, you should complete the next two chapters (Create Collection and Create Document) before checking if the database exists!
You can check if a database exists by listing all the databases in the system:
Example
Return the list of databases in the system:
print(myclient.list_database_names())
Or you can check a specific database by name:
Example
Check if "mydatabase" exists:
dblist = myclient.list_database_names() if "mydatabase" in dblist: print("The database exists.")
- Previous Page MongoDB Introduction
- Next Page MongoDB Create Collection