8

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 ?

2
  • 1
    Do you want to split your records into separate words and return these distinct words or simply return distinct values for word key? Commented Nov 3, 2013 at 20:03
  • No, my intention id to select unrepeatable words from collection. Commented Nov 4, 2013 at 13:40

6 Answers 6

12

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();
Sign up to request clarification or add additional context in comments.

2 Comments

The LINQ interface provided by the C# driver executes its queries via MongoDB, so it's not retrieving all records and then filtering them in code and is typically just as efficient.
@JohnnyHK, thanks for your correction. I actually thought about support of linq by C# driver but wasn't entirely sure. I've corrected answer.
3

this work´s for me

Collection.Distinct<string>("ColumnNameForDistinct", FilterDefinition<T>.Empty).ToListAsync()

Comments

1

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.

Comments

1

The MongoCollection.Distinct Method (String) V2.0 is Legacy

for new version API like 2.4 use:

FieldDefinition<yueyun.land,string> field = "FirstName";
var bx = _yueyunlands.Distinct<string>(field, Builders<yueyun.land>.Filter.Empty).ToList();

Comments

1

If you want to filter first and get distinct afterwards and also do all of these at MongoDB side, you can use the following example. In this example I applied a filter, got distinct values and finally got count:

        var filter = Builders<Logs>.Filter.Ne(x => x.Id, null);
        var count = collection.Distinct(x => x.Id, filter).ToList().Count();

Comments

0

MongoDB doesn't have a built in operator to split a string of words from a query as there's not a way to split a string, then run a "distinct" operation on it.

One option would be to create a MapReduce and do the split in the MapReduce code and count each word. You can't do this with just C# code.

A second, and possibly simpler option would be to pre-split the field into words so that you could use one of the distinct operators:

{ "word": [ "some", "text"] }

Then:

dbCollection.Distinct("word");

This would of course work if you just want to treat the entire string as a "word" rather than each word separately . MapReduce's aren't real-time ... the pseudo-code would be:

map = function() {
  var splits = this.word.split(' ');
  for(var i = 0, l = splits.length; i < l; i++) {
     emit(splits[i], 1);
  }
}

reduce = function(word, vals) {
   var count = 0;
   for(var i=0, l=vals.length; i < l; i++) {
       count += vals[i];
   }
   return count;
}

When you run the MapReduce, it would be a collection of the number of occurrences of each word.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.