Search code examples
pythonmongodbpymongo

How do I create a new database in MongoDB using PyMongo?


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?


Solution

  • 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.