Python MongoDB create collection

Collections in MongoDB are similar to tables in SQL databases.

Create collection

To create a collection in MongoDB, use the database object and specify the name of the collection to be created.

If it does not exist, MongoDB will create the collection.

Example

Create a collection named "customers":

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

Run Instance

Important Tip:Collections in MongoDB are not created before content is obtained!

MongoDB will wait until you have inserted documents before creating a collection in actuality.

Check if the 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 (Creating Documents) 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())

Run Instance

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.")

Run Instance