Mongoengine unique_with

I am using mongoengine with MongoDB. I have to create a document in which the tuple (merchant_id, order_id, event_type) must be a unique key.

Until now, I have always considered uniqueness limited to two fields. So, the following works -

merchant_id = StringField(required = True)
order_id = StringField(required = True, unique_with = 'merchant_id')

Now I'm trying to do this for three fields -

merchant_id = StringField(required = True)
order_id =  StringField(required = True)
event_type = StringField(
    required = True,
    unique_with = ['merchant_id', 'order_id'])

But that does not work. I do not get an error in the module. But if I enter the data as -

merchant_id = 'Merchant1'
order_id = 'Order1'
event_type = 'Event1'

and then try to add other data with the same merchant_idand order_idbut with a different one event_id, then it gives an error about duplicating the key.

I also tried:

merchant_id = StringField(required = True)
order_id =  StringField(required = True)
event_type = StringField(
    required = True,
    unique_with = ('merchant_id', 'order_id'))
+6
source share
3 answers

, , . , , . , dropDups.

+1

meta = {
    'indexes': [
        {'fields': ('merchant_id', 'order_id'), 'unique': True}
    ]
}
+7

Make sure that indexes are created, otherwise neither 'unique': Trueindexes nor fields unique_withwill work.

meta = {
    'auto_create_index': True
}
0
source

All Articles