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 using 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" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With