C# MongoDB Distinct Query Syntax
Asked Answered
P

2

10

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.

Prefrontal answered 1/3, 2016 at 14:7 Comment(0)
L
16

You could try the following approach:

var filter = new BsonDocument();
var categoriesList = await blogContext.Articles.DistinctAsync<string>("categories", filter);
Leatherneck answered 1/3, 2016 at 14:40 Comment(3)
I'd prefer DistinctAsync<dynamic> instead of DistinctAsync<string> as it's safer than strict typecasting. Just my two cents. otherwise, good solution.Insured
@Insured I concur, though solution is coming from the OP's perspective where they are expecting a distinct string list.Leatherneck
Thank you very much for your answer. I used this, based on what you said: var categoriesList = await blogContext.Articles.Distinct<string>("categories", "{}").ToListAsync();Prefrontal
C
2

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

For example:

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

Ciera answered 26/6, 2020 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.