开发者

Mongoengine unique_with

I am using mongoengine with MongoDB. I have to make a Document in which the tuple (merchant_id, order_id, event_type) has to be a unique key.

Till now, I have always dealt with uniqueness being 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 t开发者_运维问答o 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 this doesn't work. I'm not getting an error in the module. But if I enter data as -

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

and then try to add another data with the same merchant_id and order_id but a different event_id, then it gives an error about being a duplicate key.

I have also tried:

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


You can specify indexes in the meta dict of the class

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


If you want to modify an existing index's parameters, you have to drop the index first and then recreate it. Of course you cannot create a unique index on collections that contain duplicates. Either you must remove the duplicates first, or use the 'dropDups' index creation option.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜