问题
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