Python MongoDB verzameling maken
- Previous Page MongoDB Create Database
- Next Page MongoDB Insert
Verzamelingen in MongoDB zijn vergelijkbaar met tabellen in een SQL-database.
Maak verzameling
Gebruik de databaseobject om een verzameling te maken en specificeer de naam van de verzameling die je wilt maken.
Als deze niet bestaat, zal MongoDB deze verzameling aanmaken.
Example
Maak een verzameling genaamd "customers":
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"]
Important Tip:Collections in MongoDB are not created before content is obtained!
Before actually creating a collection, MongoDB will wait until you have inserted a document.
Check if collection exists
Remember: In MongoDB, collections are not created before content is retrieved, so if this is your first time creating a collection, you should complete the next chapter (create document) before checking if the collection exists!
You can check if a collection exists in the database by listing all collections:
Example
Return a list of all collections in the database:
print(mydb.list_collection_names())
Or you can check a specific collection by name:
Example
Check if the "customers" collection exists:
collist = mydb.list_collection_names() if "customers" in collist: print("The collection exists.")
- Previous Page MongoDB Create Database
- Next Page MongoDB Insert