MongoDB 的 DistinctAsync C# 驱动程序抛出 无法从 BsonType 'String' 反序列化'List<String>'



我有一个文档,其中包含字符串标签列表。我正在寻找集合中的所有不同标签,以字符串列表的形式返回。

public class TestGetDistinctDocument 
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<string> Tags { get; set; }
}

我可以使用DistinctDistinctAsync为其他字段实现此目的

var result = collection.Distinct(doc => doc.Name, FilterDefinition<TestGetDistinctDocument>.Empty);
return await result.ToListAsync();

返回集合中所有不同"名称"的列表。但是对标签抛出做同样的事情

System.FormatException : Cannot deserialize a 'List<String>' from BsonType 'String'.

这是引发异常的代码:

var cursor =  await collection.DistinctAsync(doc => doc.Tags, filter);
var distinctTags = await cursor.ToListAsync();
return distinctTags.SelectMany(tag => tag).ToList();

我正在使用 mongo-csharp 驱动程序版本 2.8

这是实现此目的的一种方法

使用FieldDefinition定义要"区分"的字段

FieldDefinition<TestGetDistinctDocument, string> field = "Tags";而不是使用 Linq 作为使用

var filter = FilterDefinition<TestGetDistinctDocument>.Empty;
FieldDefinition<TestGetDistinctDocument, string> field = "Tags";

然后在参数中传递DistinctAsycDistinct

var cursor =  collection.DistinctAsync(field, FilterDefinition<TestGetDistinctDocument>.Empty);
return await cursor.Result.ToListAsync();

这给出了所有TestGetDistinctDocument的不同标签列表。

相关内容

最新更新