开发者

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

开发者 https://www.devze.com 2023-03-27 17:48 出处:网络
MongoDB allows for an index on a key inside of an embedded document: db.things.ensureIndex({\"address.city\": 1})

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

精彩评论

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