Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a combined set of fields unique in Mongodb in Python

I want to create a table where two of its fields combine to form an index field. My Python code for creating the table is as follows. What I want to do is make the combined fields course_name and group_name unique so that no two groups with the same course_name and group_name can be created. Can someone please help me with this?

class SocialGroup(Document):
    timestamp = DateTimeField(default=datetime.now)
    course_name = StringField()
    group_name = StringField(choices=[('A', 1), ('B', 1), ('C', 1),('D', 1), ('E', 1), ('F', 1), ('None',1)], default="None")
like image 586
Paba Avatar asked Feb 21 '13 08:02

Paba


2 Answers

You can specify indexes in the meta dict of the class:

class SocialGroup(Document):
    timestamp = DateTimeField(default=datetime.now)
    course_name = StringField()
    group_name = StringField(choices=[('A', 1), ('B', 1), ('C', 1),('D', 1), ('E', 1), ('F', 1), ('None',1)], default="None")
    meta = {
        'indexes': [
            {'fields': ('course_name', 'group_name'), 'unique': True}
        ]
    }
like image 65
JohnnyHK Avatar answered Oct 05 '22 14:10

JohnnyHK


From: http://docs.mongoengine.org/guide/defining-documents.html#uniqueness-constraints

You may also specify multi-field uniqueness constraints by using unique_with, which may be either a single field name, or a list or tuple of field names

In your case:

class SocialGroup(Document):
    timestamp = DateTimeField(default=datetime.now)
    course_name = StringField()
    group_name = StringField(choices=[('A', 1), ('B', 1), ('C', 1),('D', 1), ('E', 1), ('F', 1), ('None',1)], default="None",
                             unique_with='course_name')

Or more complicated:

group_name = StringField(choices=[('A', 1), ('B', 1), ('C', 1),('D', 1), ('E', 1), ('F', 1), ('None',1)], default="None",
                         unique_with=['course_name', 'another_field', 'more_field'])
like image 43
Hieu Avatar answered Oct 05 '22 15:10

Hieu