Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying collection name with MongoEngine

Once content is added the name of the collection is defaulted to the name of the class. Is it possible to specify the collection name or is my approach wrong? Using the code I have my collection is then named "mongo_engine_python" by default.

from mongoengine import *

try:
    connect(
        db='MongoEngine_Test',
        host="mongodb://localhost:27017/"
    )
    print("Connection successful")
except:
    print("Unable to connnect") 

class MongoEnginePython(Document):
    item_name = StringField(max_length=200, required=True)
    item_price = IntField(default=0)
like image 373
Reez0 Avatar asked Dec 30 '18 10:12

Reez0


1 Answers

Didn't look at the docs properly. Here it is:

2.3.4. Document collections

Document classes that inherit directly from Document will have their own collection in the database. The name of the collection is by default the name of the class, converted to lowercase (so in the example above, the collection would be called page). If you need to change the name of the collection (e.g. to use MongoEngine with an existing database), then create a class dictionary attribute called meta on your document, and set collection to the name of the collection that you want your document class to use:

class Page(Document):
    title = StringField(max_length=200, required=True)
    meta = {'collection': 'cmsPage'}
like image 97
Reez0 Avatar answered Oct 15 '22 07:10

Reez0