c# - Mongo C# 驱动程序 - 如何将 ToLower() 应用于 DistinctAsyc
问题描述
我正在使用 MongoDB 从 MongoDB 中检索字符串列表DistinctAsync
。问题是结果是不同的,除了我得到一些全大写的值和一些小写的值,这当然算作不同的。
我如何将 a.ToLower()
应用于此查询?
public async Task<List<string>> GetAllAuthorsUserNames()
{
var filter = Builders<Episode>.Filter.Where(x => x.CreatedBy != null);
var cursor = await GetCollection().DistinctAsync(o => o.CreatedBy, filter);
return cursor.ToList();
}
我已经尝试过了,但它不起作用:
var cursor = await GetCollection().DistinctAsync(o => o.CreatedBy.ToLower(), filter);
解决方案
您可以采取多种方法来产生您想要的结果。有些是:
仅以小写形式存储作者的姓名(或至少以一致的方式存储,这样您就不必首先转换他们的姓名以产生不同的姓名),在这种情况下,仅一个不同的查询就足以让您获得期望的结果。
从当前数据中获取不同作者的姓名后,将他们的姓名映射到内存中各自的小写版本,然后对其应用另一个不同的函数,以获取所有作者的小写和不同形式的姓名。这看起来像:
var filter = ...
var cursor = await GetCollection().DistinctAsync(v => v.CreatedBy, filter);
var list = await cursor.ToListAsync();
var names = list.Select(v => v.ToLower()).Distinct().ToList();
- 使用聚合。基本上,您可以将
project
所有作者的姓名转换为各自的小写形式(参见:toLower),然后将group
所有投影的小写名称转换为一个集合(参见:addToSet)。该集合将是您可以从聚合结果中提取的结果。
My opinion is that you should consider altering your data so as to not add unnecessary computational complexity which takes up valuable resources. If that is not possible, but the names themselves are relatively few, you can use the second approach. Use the third approach with the understanding that it is not the ideal and it will add to more processing on the part of your DBMS.
推荐阅读
- sitecore8 - 体验分析报告数据库中的 SiteNames 表 - 如何/何时填充?
- sql-update - 使用 SlashDb 更新数据
- sql-server - 控制 INSERT 和 UPDATE 语句的执行顺序
- async-await - 带有异步的 Linq-to-entity 子查询
- ruby-on-rails - 如何在 Rails 服务对象中显示 Flash 消息
- android - Robotium:仅在 alertDialog 中单击文本,而不是在下面的活动中
- angular - 由于未处理的 Promise Rejection 导致测试失败
- android - TextView:缩进中的缩进?
- wpf - 有没有办法在没有背景覆盖的情况下显示 Mahapps 消息对话框?
- python-3.x - PYTHON FLASK 应用程序(带有 KERAS 和 tensorflow 后端):无法在运行时加载模型:“会话图为空”