【问题标题】:C# MongoDB Driver Aggregate() always throw cast exceptionC# MongoDB Driver Aggregate() 总是抛出强制转换异常
【发布时间】:2022-06-15 03:46:12
【问题描述】:

我正在尝试使用 Lookup 功能加入集合:

var docs = await Items
    .Aggregate()
    .Lookup("categories", "categoryId", "_id", "category")
    .ToListAsync();

但我总是得到:

System.InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonString' to type 'MongoDB.Bson.BsonBoolean'.

并且返回结果中的单个对象有很多属性异常:

即使我只使用 Aggregate():

var docs = await Items
    .Aggregate()
    .ToListAsync();

它仍然返回相同的结果。

【问题讨论】:

  • 您能否提供两个收集的样本数据以用于复制目的?谢谢。
  • 真的没关系,但是假设我有 Item 有 Id、Title 和 CategoryId 和 Category 有 Id 和 Name
  • and the single object in the returned result has a lot of properties that bears exception: - 这是预期的自抛出异常只是说您无法将文档转换为bool/int 等。您应该提供您的数据。我认为错误不是关于聚合,而是关于映射你的数据
  • 这些属性属于 BsonDocument 对象。事实上,我的模型中并没有很多这些类型,所以没有映射可做!

标签: c# asp.net mongodb-.net-driver


【解决方案1】:

Aggregate() 函数默认返回BsonDocument 对象中的结果。换句话说,它与Aggregate<BsonDocument>() 相同。

所以为了避免这种异常,而不是将文档映射到BsonDocument 列表,我必须将它映射到我自己的对象,在我的例子中,PopultedItem 表示项目数据及其类别数据。

var docs = await Items
    .Aggregate<PopultedItem>()
    .Lookup("categories", "categoryId", "_id", "category")
    .ToListAsync();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    相关资源
    最近更新 更多