1

I am trying to insert documents in which a same property has null value while I have defined a unique index on it. I receive error because of same null values for that field. I used sparse: true, but it seems it works when target field does not exists. I insist to have the property with null value. Is there any solution?

weera
  • 884
  • 1
  • 10
  • 21

1 Answers1

0

Ohh, for a long time, out of ignorance, I was tinkering with this problem. I don't know if this is correct but it worked for me.

type A struct {
    Series *string `json:"series" bson:"series,omitempty"`
    Number *string `json:"number" bson:"number,omitempty"`
}
    indexNames := "series_number_index"
    unique := true  
    sparse := true 
    indexm := []mongo.IndexModel{           
                  {
                    Keys: bsonx.Doc{
                        {Key: "series", Value: bsonx.Int32(1)},
                        {Key: "number", Value: bsonx.Int32(1)},
                    },
                    Options: &options.IndexOptions{
                        Name:   &indexNames,
                        Unique: &unique,
                        Sparse: &sparse,
                    },          
                 },
             }
Alex A
  • 323
  • 1
  • 8