Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 using mongoengine?

like image 630
mattexx Avatar asked Jan 19 '23 00:01

mattexx


2 Answers

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

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

That's all.

like image 131
dae Avatar answered Jan 31 '23 07:01

dae


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" })
like image 25
dcrosta Avatar answered Jan 31 '23 07:01

dcrosta