【问题标题】:Can not get mongodb Aggregate query result in c#在c#中无法获取mongodb聚合查询结果
【发布时间】:2021-04-24 13:00:30
【问题描述】:

我创建了两个数据模型并尝试使用 mongoDb C# 驱动程序对其应用不同的查询。 这是get方法中的查询

var res = _postCollection.Aggregate().Lookup("_commentCollection", "Comments", "_id", "result").ToList();
return OK(res)

但是当我从邮递员那里调用方法时得到以下结果

System.InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonObjectId' to type 'MongoDB.Bson.BsonBoolean'.
   at get_AsBoolean(Object )
   at System.Text.Json.JsonPropertyInfoNotNullable`4.OnWrite(WriteStackFrame& current, Utf8JsonWriter writer)
...............

【问题讨论】:

    标签: c# .net mongodb .net-core bson


    【解决方案1】:

    你的问题是投射!您想尝试将对象类型“MongoDB.Bson.BsonObjectId”转换为类型“MongoDB.Bson.BsonBoolean”。这是不可能的,您将收到异常

    【讨论】:

    • 不知道MongoDB.Bson.BsonBoolean是哪来的,我没用过这个类型
    【解决方案2】:

    查找的参数是Ref

    string foreignCollectionName,
    FieldDefinition<TResult> localField,
    FieldDefinition<TForeignDocument> foreignField,
    FieldDefinition<TNewResult> as,
    AggregateLookupOptions<TForeignDocument, TNewResult> options
    

    所以 localField 和 foreignField 必须是同一类型。在您的情况下,它们是错误中清楚显示的不同类型

    System.InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonObjectId' to type 'MongoDB.Bson.BsonBoolean'.
       at get_AsBoolean(Object )
       at System.Text.Json.JsonPropertyInfoNotNullable`4.OnWrite(WriteStackFrame& current, Utf8JsonWriter writer)
    

    这是 SO 上的 similar question 可以帮助您。

    【讨论】:

    • 两者都是同一种类型,我在 mongo shell 上测试过,它可以工作,但不是在这里
    • @Hridoy_089 类型是?
    • 类型 BsonObjectId
    • @Hridoy_089 此列的默认名称是 _id 您是否为第二个集合更改了?
    • 我使用了 public ObjectId Id { get;放; } 两个集合
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2021-07-01
    相关资源
    最近更新 更多