Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select distinct mongodb C#

Tags:

c#

mongodb

I have to select distinct records from my simple mongo db database. I have many simple records these records looks like this :

{"word":"some text"}

My code is very simple.

    const string connectionString = "mongodb://localhost";
    var client = new MongoClient(connectionString);

    MongoServer server = client.GetServer();
    MongoDatabase database = server.GetDatabase("text8");
    MongoCollection<Element> collection = database.GetCollection<Element>("text8");
    MongoCursor<Element> words = (MongoCursor<Element>)collection.FindAll();

But I have't idea how to select distinct word's from database. Could someone can give me some advice ?

like image 988
Konrad Avatar asked Nov 03 '13 17:11

Konrad


3 Answers

MongoDB API has a distinct aggregation command, which returns distinct values found for a specified key in a collection. You can also use it from C# Driver:

var distinctWords = collection.Distinct("word");

where collection - is an instance from your example. This query will return all distinct values of word field in the collection.

Also, as @JohnnyHK mentioned in comment, you can use linq approach, since it is supported by C# driver:

var distinctWords = collection.AsQueryable<Element>().Select(e => e.Word).Distinct();
like image 121
Shad Avatar answered Oct 23 '22 10:10

Shad


this work´s for me

Collection.Distinct<string>("ColumnNameForDistinct", FilterDefinition<T>.Empty).ToListAsync()
like image 30
D__ Avatar answered Oct 23 '22 09:10

D__


My guess would be to make "word" an index on this db. Then using some linq to query it in a simple expression: var res = col.Query().Select(e => e.word).Distinct();

This would result in reading all words from the index.

like image 1
Hylaean Avatar answered Oct 23 '22 11:10

Hylaean