MongoDb与查询C#驱动程序不同 [英] MongoDb Distinct with query C# driver

查看:95
本文介绍了MongoDb与查询C#驱动程序不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用db.collection.distinct(field, query)命令,该命令记录在此处.我正在尝试使用C#驱动程序来调用它,该驱动程序已记录在这里.

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.

当前我正在使用代码:

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

其中messageId是一个字符串,搜索功能执行以下操作:

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;
    }

因此,应将其转换为:

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

虽然运行时出现以下错误:

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

仅单个字段支持Distinct.与Distinct一起使用的投影必须解析为文档中的单个字段."

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

我正在使用Mongo 2.4.9和官方的C#驱动程序1.8.3

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

推荐答案

.distinct()方法是一个较旧的实现,它更多是包装mapReduce的便捷方法.对于涉及简单操作的更多内容,您应该使用 .aggregate() .

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().

因此,shell等效:

So the shell equivalent:

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

文档仅构成BSON文档链. 此处.

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

这篇关于MongoDb与查询C#驱动程序不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆