Search code examples
c#.netmongodbmongodb-.net-driver

Querying tags from mongodb with c# driver


I have a blog where i store tags inside of the blogposts. The post basically consist of a property like:

public List<string> Tags { get; set; }

What i want to do is to get all the unique tags from the database as efficient as possible. Right now I do like this:

var tagList = postCollection.AsQueryable().Select(x => x.Tags)
                .ToList();

Which gives me a list of lists containing the tags (I can then extract the tags from the lists and select them distict using Linq). I understand that this is not the most efficient way but I do not get how I can do this using the C# driver? I should probably have an index of some sort and I should probably query in an other way but how?


Solution

  • You can directly query for the distinct list of tags using Distinct:

    var tagList = postCollection.Distinct<string>("Tags");