MongoDb Distinct with query C# driver

我的未来我决定 提交于 2019-12-10 10:31:00

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/22598750/mongodb-distinct-with-query-c-sharp-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!