使用MongoEngine指定集合名称 [英] Specifying collection name with MongoEngine
问题描述
一旦添加了内容,集合的名称将默认为类的名称.是否可以指定集合名称,或者我的方法是否错误?使用我收集的代码,默认情况下将其命名为"mongo_engine_python".
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)
推荐答案
未正确查看文档.在这里:
Didn't look at the docs properly. Here it is:
2.3.4.文件集
直接从Document继承的Document类将具有其 在数据库中拥有自己的集合.集合的名称是 默认类的名称,转换为小写(因此在 上面的示例中,该集合称为页面).如果你需要 更改集合的名称(例如,将MongoEngine与 现有数据库),然后创建一个名为的类字典属性 元在您的文档上,然后将collection设置为 您希望文档类使用的集合:
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'}
这篇关于使用MongoEngine指定集合名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!