Search code examples
python-3.xmongodbmongoengineflask-mongoengine

How can I get a list of collections in a database using MongoEngine?


I'd like to know what call I can make from a python MongoEngine instance to get a list of collection names from my mongodb database? If I were using pymongo directly I could call db.list_collection_names(), but I can't find a similar call from MongoEngine. Specifically I'm using flask-mongoengine if that matters.


Solution

  • MongoEngine

    from mongoengine import connect
    
    db_name = 'test'
    connection = connect(db_name)
    connection.get_database(db_name).list_collection_names()
    

    Flask-MongoEngine

    from flask import Flask
    from flask_mongoengine import MongoEngine
    
    app = Flask(__name__)
    db = MongoEngine(app)
    #app.config.from_pyfile('the-config.cfg')
    #app.config['MONGODB_SETTINGS'] = {}
    db.get_db().list_collection_names()