MongoDB - how to avoid duplicates or have a conditional index in many to many

Viewed 22

I have an events collection where i need to have a unique constraint but conditionally, so i hav an event which can have many records but i need to only have 1 customer per event, how is this done using mongo indexes to avoid duplicate entries

        {
            event: "Rolling stones",
            customer_id: 1,     
        },
        {
            event: "Rolling stones",
            customer_id: 1,     
        },
        {
            event: "Rolling stones",
            customer_id: 2,     
        },
        {
            event: "Rolling stones",
            customer_id: 3,     
        },
1 Answers

you can create a compound index with a unique constraint like this:

db.Events.createIndex(
    {
        event: 1,
        customer_id: 1
    },
    {
        unique: true
    }
)

it will only allow the following record to be added once:

        {
            event: "Rolling stones",
            customer_id: 1,     
        }

you can add same event with different customer ids like:

        {
            event: "Rolling stones",
            customer_id: 2,     
        }

because uniqueness is enforced on the combination of index keys.

Related