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 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 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'))
MongoEngine allows you to specify that a field should be unique across a collection by providing unique=True to a Field‘s constructor. If you try to save a document that has the same value for a unique field as a document that is already in the database, a NotUniqueError will be raised.
Defining documents — MongoEngine 0.23.1 documentation 2.3. Defining documents ¶ In MongoDB, a document is roughly equivalent to a row in an RDBMS. When working with relational databases, rows are stored in tables, which have a strict schema that the rows follow.
By default, MongoDB generates a unique ObjectID identifier that is assigned to the _id field in a new document before writing that document to the database. In many cases the default unique identifiers assigned by MongoDB will meet application requirements. However, in some cases an application may need to create custom unique identifiers, such as:
How to get unique values from MongoDB collection? To get unique values and ignore duplicates, use distinct () in MongoDB. The distinct () finds the distinct values for a specified field across a single collection and returns the results in an array. Display all documents from a collection with the help of find () method −
You can specify indexes in the meta dict of the class
meta = {
'indexes': [
{'fields': ('merchant_id', 'order_id'), 'unique': True}
]
}
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