2

How can I create an array of unique elements in MongoDB c# driver,

I don't want to check every time if this element already in the array or not.

suppose :

list=[1,2,3,4]

then I shouldn't be able to add duplicate element (such as 3 )

Zeeshan Adil
  • 1,937
  • 5
  • 23
  • 42
akash
  • 727
  • 5
  • 13
  • I assume you are referring to uniqueness on insert? If so, check out a unique index option. – barrypicker Oct 24 '19 at 15:25
  • i expect uniqueness on insert and update. how to create unique index on array elements in MongoDB c# driver – akash Oct 24 '19 at 15:28
  • HI @akash - the index is created on the database. I suspect you could issue a command via c# driver, but then again creating indexes is not something typically done more than once. With that in mind you probably would find it easier to create an index using the mongo shell. Here is the docs... https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/ – barrypicker Oct 24 '19 at 17:34
  • @barrypicker -if i create an index on database, then i think array will be unique not the elements in array. – akash Oct 25 '19 at 12:51
  • 1
    This post should give you a head start https://stackoverflow.com/a/43052168/1859959. I mean the "BUT if you strictly use $addToSet with the index" part – ntohl Oct 25 '19 at 13:27
  • @akash - yes, you are correct. Please disregard my advice to use a unique index on arrays. Unique Multi-key indexes ensure selectivity of the parent document, not the elements in array embedded in the document. Sorry for the misdirection. – barrypicker Oct 25 '19 at 18:14

1 Answers1

2

You can use the AddToSet or AddToSetEach method, every time you create or update the array, as mentioned in the comments:

var update = Builders<Entity>.Update.AddToSetEach(e => e.Items, new [] {1, 2});
collection.UpdateOne(new BsonDocument(), update, new UpdateOptions { IsUpsert = true });

And you can define a schema validation when creating the collection, to ensure that duplicate items will never be allowed (an error would be thrown on insert/update, “Document failed validation”).

You can define the schema in the MongoDB shell, or here is how to do it in C#:

var options = new CreateCollectionOptions<Entity>
{
    ValidationAction = DocumentValidationAction.Error,
    ValidationLevel = DocumentValidationLevel.Strict,
    Validator = new FilterDefinitionBuilder<Entity>().JsonSchema(new BsonDocument
    {
        { "bsonType", "object" },
        { "properties", new BsonDocument("Items", new BsonDocument
            {
                { "type" , "array" },
                { "uniqueItems", true }
            })
        }
    })
};

database.CreateCollection("entities", options, CancellationToken.None);

where Entity is an example class like this:

public class Entity
{
    public ObjectId Id { get; set; }
    public int[] Items { get; set; }
}

Here are the API docs for CreateCollectionOptions and in the unit tests you can see examples of usage - e.g. JsonSchema(). Unfortunately I don't see anything in the reference docs with more thorough explanations.

sheilak
  • 5,833
  • 7
  • 34
  • 43