Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb Distinct with query C# driver

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

like image 313
Andrew Poland Avatar asked Jul 01 '26 18:07

Andrew Poland


1 Answers

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.

like image 163
Neil Lunn Avatar answered Jul 06 '26 06:07

Neil Lunn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!