3

I am trying to use the db.collection.distinct(field, query) command, documented here. I am trying to call this with the C# driver, documented here.

Currently I am using the code:

_repository.Search(item.searchCriteria).Select(i => i.messageId).Distinct().ToList()

where messageId is a string and the Search function does:

//Create search accross all properties of type.
public IQueryable<SearchType> Search(SearchType entity)
    {
        Type entityType = entity.GetType();
        var propertiesToSearch = entityType.GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
        query = _collection.AsQueryable();
        query = query.WhereAnd(
            query.ElementType,
            propertiesToSearch.Select(p => new SearchCriteria()
                {
                    Column = p.Name,
                    Value = p.GetValue(entity),
                    Operation = WhereOperation.Equal
                }).ToArray());
        return query;
    }

So this should get converted to:

db.collection.distinct("messageId", { $and: [ { prop1: "" }, { prop2: "" } ]  })

I am getting the following error when this is run though:

"Distinct is only supported for a single field. Projections used with Distinct must resolve to a single field in the document."

I am using Mongo 2.4.9 and the official C# driver 1.8.3

2
  • did you try aggregate/group. that should give you what you are looking for. Commented Mar 24, 2014 at 0:41
  • Have you tried trying without your search function experimentally? Commented Mar 24, 2014 at 0:55

1 Answer 1

4

The .distinct() method is an older implementation that is more of a convenience method wrapping mapReduce. For anything more involved that simple operations you should use .aggregate().

So the shell equivalent:

db.collection.aggregate([
    { "$match": { "$and": [ { "prop1": "" }, { "prop2": "" } ] } },
    { "$group": { "_id": "$messageId" } }  
])

The documents are just formed as a chain of BSON documents. There are various examples here.

Sign up to request clarification or add additional context in comments.

3 Comments

@Andrew does the change here better suit your purpose? You really should be using aggregate here. Which is the point.
Thanks, that's what I wanted to achieve :)
@NeilLunn The distinct command pre-dates the Aggregation Framework .. however it is implemented in C++ and unrelated to MapReduce (ref: db/commands/distinct.cpp). The distinct() helper in the shell is a wrapper for the distinct command.

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.