Search code examples
c#mongodbmongodb-indexes

Insert many rows and check for duplicates in both field. Mongodb C#


I've got 2 fields in a collection, the collection is empty and need to be populated. This is how it is defined:

public class MyColl
{
    [BsonElement("id")]
    public ObjectId id { get; set; }
    public ObjectId A { get; set; }
    public ObjectId B { get; set; }
}

what i want to achieve is this:

Let K be a pair to be insert e.g. K=(x,y) i want that mongodb before perform insertion of the rows check the following constraints:
1) if A==x AND B==y and this already exist in collection, don't insert that.
2) if A==y AND B==x and this already exist in collection, don't insert that.
3) if A==x AND B==y and already exist A==y and B==x, don't insert that.
4) if A==y AND B==x and already exist A==x and B==y, don't insert that.

I think that what i need is a unique compound index on (A,B) and (B,A) to check for 1 and 2 but i don't know what to do for other two constraints.
How can i do that?


Solution

  • I solved this problem modifying a little bit the definition of the class:

    public class MyColl {
        [BsonElement("id")]
        public ObjectId id { get; set; }
        public ObjectId A { get; set; }
        public ObjectId B { get; set; }
        public string C {get;set;}   }
    

    then everytime i add an element i create a list:

    List<string> elements = new List<string>();
    elements.Add(b.toString())
    elements.Add(c.toString())
    elements.Sort();
    MyColl.C = string.Concat(elements[0],elements[1]);
    

    C contains indexes sorted in alphabetical order, so making it as unique index will cause an exception everytime a duplicate is insert.