Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C# Driver Unique Index PartialFilterExpression for when isArchived is false

Tags:

c#

mongodb

I have a collection of items that can be deleted. I would like to have a unique index on the name so long as isArchived is false. I can do it with the mongo command line, but I can't seem to find much documentation for the C# driver. Currently we have the index:

        await JobsCollection.Indexes.CreateOneAsync("{Name: 1}", new CreateIndexOptions
        {
            Unique = true
        });

I assume that would become something close to:

        await JobsCollection.Indexes.CreateOneAsync("{Name: 1}", new CreateIndexOptions<JobModel>
        {
            Unique = true,
            PartialFilterExpression = /*something here*/
        });

But I am not entirely sure what should go in the 'something here' spot. Can I just do a string like "{ IsArchived: { $eq : false } }" or is there a better way? Thanks.

like image 977
Cory-G Avatar asked Oct 21 '25 11:10

Cory-G


1 Answers

A More typed example:

await JobsCollection.Indexes.CreateOneAsync(
                Builders<JobModel>.IndexKeys
                    .Ascending(i => i.Name), 
                new CreateIndexOptions<JobModel>
                {
                    Unique = true,
                    PartialFilterExpression = Builders<JobModel>.Filter.Eq(i => i.IsArchived, true)
                });
like image 109
ilcorvo Avatar answered Oct 24 '25 02:10

ilcorvo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!