إنشاء قاعدة بيانات MongoDB باستخدام Python

إنشاء قاعدة بيانات

لإنشاء قاعدة بيانات في MongoDB، يجب أولاً إنشاء كائن MongoClient، ثم تحديد عنوان IP والاسم الذي سيتم إنشاء قاعدة البيانات به.

إذا كانت قاعدة البيانات غير موجودة، سينشئ MongoDB قاعدة البيانات ويقوم بإنشاء الاتصال.

Instance

إنشاء قاعدة بيانات تُدعى "mydatabase":

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]

Run Instance

Important Note:Databases in MongoDB will not be created before accessing the content!

Before actually creating a database (and collection), MongoDB will keep waiting for you to create a collection (table) with at least one document (record).

Check if the database exists

Remember: In MongoDB, databases will not be created before accessing the 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 databases in the system:

Instance

Return the list of databases in the system:

print(myclient.list_database_names())

Run Instance

Or you can check a specific database by name:

Instance

Check if "mydatabase" exists:

dblist = myclient.list_database_names()
if "mydatabase" in dblist:
  print("The database exists.")

Run Instance