Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# MongoDB Distinct Query Syntax

I am trying to get the distinct values from a field in MongoDB. I am having real trouble with the Syntax. Using mongoshell it's relatively easy to do, this is the query I run:

db.cmstest.distinct("categories")

This query returns an array of strings with all the distinct values.

Now I am trying to get the syntax right using the latest official MongoDB Drivers, but not to much success. This is my code, which is unsuccessful:

var categoriesList = await blogContext.Articles.DistinctAsync<List<string>>("categories", "");

Mind you categories is a List<string>.

Could anyone help shed some light? I've tried looking both in the documentation and online and haven't found much.

Thank you in advance.

like image 912
Yiannis P. Avatar asked Mar 01 '16 14:03

Yiannis P.


2 Answers

You could try the following approach:

var filter = new BsonDocument();
var categoriesList = await blogContext.Articles.DistinctAsync<string>("categories", filter);
like image 151
chridam Avatar answered Sep 19 '22 22:09

chridam


Better yet you can use a lambda expression to be type safe.

For example:

await this.Collection.DistinctAsync(flow => flow.timestampDate, new BsonDocument());

like image 25
Jack Avatar answered Sep 18 '22 22:09

Jack