mongoengine - 嵌入式文档内部键的索引?

时间:2011-08-10 16:32:42

标签: python mongodb mongoengine

MongoDB允许嵌入文档内部键的索引:

db.things.ensureIndex({"address.city": 1})

有没有办法用mongoengine做到这一点?

2 个答案:

答案 0 :(得分:4)

class Nested(EmbeddedDocument):
    a = StringField(unique=True)
    b = StringField()

class Outer(Document):
    inner = EmbeddedDocumentField(Nested)
    c = StringField()
    meta = {"indexes": ['inner.a']}

就是这样。

答案 1 :(得分:2)

您可以使用unique=True

在嵌入文档上指定字段
>>> class Nested(EmbeddedDocument):
...     a = StringField(unique=True)
...     b = StringField()
... 
>>> class Outer(Document):
...     inner = EmbeddedDocumentField(Nested)
...     c = StringField()
... 
>>> o = Outer()
>>> o.c = 'abc'
>>> o.inner = Nested(a='a', b='b')
>>> o.save()
>>> o2 = Outer()
>>> o2.c = 'abc'
>>> o2.inner = Nested(a='a', b='B')
>>> o2.save()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mongoengine/document.py", line 176, in save
    raise OperationError(message % unicode(err))
mongoengine.queryset.OperationError: Tried to save duplicate unique keys (E11000 duplicate key error index: test.outer.$inner.a_1  dup key: { : "a" })