开发者

mongoengine - index on a key inside of an embedded document?

MongoDB allows for an index on a key inside of an embedded document:

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

Is there a way to do this us开发者_Python百科ing mongoengine?


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

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

That's all.


You can specify a field on an embedded document with 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" })
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜