Search code examples
mongodbmongodb-.net-driver

Multiple composite keys


This is my entity:

{
     name: "",
     list: [{
       a: 1,
       b: 1   
     }]
}

I want to create two index, one by name and other for a and b together.

Example: trying to insert a=1 and b=1 twice must throw an error.

My mongodb driver is 2.

For name I did it work like that:

    await collection.Indexes.CreateOneAsync(Builders<MyEntity>.IndexKeys.Ascending(m => m.Name), new CreateIndexOptions()
    {
        Unique = true,
        Sparse = true
    });

How can I do it for two properties in my list?


Solution

  • From the C# side, you can use the IndexKeys.Combine helper to create such an index:

    await coll.Indexes.CreateOneAsync(Builders<MyEntity>.IndexKeys.Combine(
           Builders<MyEntity>.IndexKeys.Ascending("list.a"), 
           Builders<MyEntity>.IndexKeys.Ascending("list.b")), new CreateIndexOptions()
            {
                Unique = true,
                Sparse = true
            });
    

    One odd behavior is that the constraints are not enforced within a single document (SERVER-1068) because indexes are not considered 'within' documents, so to speak. In other words, you could always insert a document list : [ {a:1, b:1}, {a:1, b:1} ], i.e. a document that has a list that contains copies. That is easy to fix on the application side, but it might be good to know.