首页 > 解决方案 > 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);

标签: c#mongodbmongodb-.net-driver

解决方案


您可以采取多种方法来产生您想要的结果。有些是:

  1. 仅以小写形式存储作者的姓名(或至少以一致的方式存储,这样您就不必首先转换他们的姓名以产生不同的姓名),在这种情况下,仅一个不同的查询就足以让您获得期望的结果。

  2. 从当前数据中获取不同作者的姓名后,将他们的姓名映射到内存中各自的小写版本,然后对其应用另一个不同的函数,以获取所有作者的小写和不同形式的姓名。这看起来像:

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();
  1. 使用聚合。基本上,您可以将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.


推荐阅读