gpt4 book ai didi

c# - Mongo C# Driver 2.0 聚合组异常

转载 作者:IT老高 更新时间:2023-10-28 12:29:43 27 4
gpt4 key购买 nike

我正在尝试使用流利的聚合界面根据多字段键为每个组选择集合中的最新记录:

        var matches = await Collection.Aggregate()
.Match(x => x.EffectiveDate >= minEffectiveDate)
.SortByDescending(x => x.LastUpdate)
.Group(key => new { key.EffectiveDate, key.ProductOid, key.InstrumentParentOid, key.ComponentOid, key.EventSummary }, g => g.First())
.ToListAsync();

但是,我得到以下异常:

System.InvalidCastException occurred
HResult=-2147467262
Message=Unable to cast object of type 'MongoDB.Driver.Linq.Expressions.SerializationExpression' to type 'System.Linq.Expressions.MethodCallExpression'.
Source=MongoDB.Driver
StackTrace:
at MongoDB.Driver.Linq.Processors.GroupSerializationInfoBinder.GetBodyFromSelector(MethodCallExpression node)
at MongoDB.Driver.Linq.Processors.GroupSerializationInfoBinder.GetAggregationArgument(MethodCallExpression node)
at MongoDB.Driver.Linq.Processors.GroupSerializationInfoBinder.VisitMethodCall(MethodCallExpression node)
at MongoDB.Driver.Linq.Translators.AggregateProjectionTranslator.BindSerializationInfo(SerializationInfoBinder binder, LambdaExpression node, IBsonSerializer parameterSerializer)
at MongoDB.Driver.Linq.Translators.AggregateProjectionTranslator.TranslateGroup[TKey,TDocument,TResult](Expression`1 idProjector, Expression`1 groupProjector, IBsonSerializer`1 parameterSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.IAggregateFluentExtensions.GroupExpressionProjection`3.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.AggregateFluent`2.<>c__DisplayClass1`1.<Group>b__0(IBsonSerializer`1 s, IBsonSerializerRegistry sr)
at MongoDB.Driver.DelegatedPipelineStageDefinition`2.Render(IBsonSerializer`1 inputSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.PipelineStageDefinition`2.MongoDB.Driver.IPipelineStageDefinition.Render(IBsonSerializer inputSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.PipelineStagePipelineDefinition`2.Render(IBsonSerializer`1 inputSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.MongoCollectionImpl`1.<AggregateAsync>d__7`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MongoDB.Driver.IAsyncCursorSourceExtensions.<ToListAsync>d__14`1.MoveNext()

好的。所以出于某种原因它不喜欢 IEnumerable 扩展方法。所以我尝试提取LINQ扩展方法:

        var matches = await Collection.Aggregate()
.Match(x => x.EffectiveDate >= minEffectiveDate)
.SortByDescending(x => x.LastUpdate)
.Group(key => new { key.EffectiveDate, key.ProductOid, key.InstrumentParentOid, key.ComponentOid, key.EventSummary }, g => g)
.ToListAsync();
return matches.Select(x => x.First());

但是:

System.InvalidCastException occurred
HResult=-2147467262
Message=Unable to cast object of type 'MongoDB.Bson.Serialization.Serializers.ArraySerializer`1[SPMO.Providers.Audit.Messages.ProductAdjustmentAuditDataDb]' to type 'MongoDB.Bson.Serialization.IBsonSerializer`1[System.Linq.IGrouping`2[<>f__AnonymousType0`5[System.Nullable`1[System.DateTime],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.String],SPMO.Providers.Audit.Messages.ProductAdjustmentAuditDataDb]]'.
Source=MongoDB.Driver
StackTrace:
at MongoDB.Driver.Linq.Translators.AggregateProjectionTranslator.TranslateGroup[TKey,TDocument,TResult](Expression`1 idProjector, Expression`1 groupProjector, IBsonSerializer`1 parameterSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.IAggregateFluentExtensions.GroupExpressionProjection`3.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.AggregateFluent`2.<>c__DisplayClass1`1.<Group>b__0(IBsonSerializer`1 s, IBsonSerializerRegistry sr)
at MongoDB.Driver.DelegatedPipelineStageDefinition`2.Render(IBsonSerializer`1 inputSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.PipelineStageDefinition`2.MongoDB.Driver.IPipelineStageDefinition.Render(IBsonSerializer inputSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.PipelineStagePipelineDefinition`2.Render(IBsonSerializer`1 inputSerializer, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Driver.MongoCollectionImpl`1.<AggregateAsync>d__7`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MongoDB.Driver.IAsyncCursorSourceExtensions.<ToListAsync>d__14`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

我的计划 B 只是忘记 Aggregate,做一个简单的 Find(),然后在 vanilla LINQ 中做一个 GroupBy(),但我想让它在 DB 上工作,因为它会更有效。

最佳答案

我遇到了同样的问题。我的解决方法不同:我没有使用 LINQ GroupBy() 客户端,而是进行了两次服务器调用。

  1. 获取我希望检索的文档的 MongoDB ObjectId,即我希望 Group() 将简单地作为 POCO 为我发出的文档。
  2. 针对步骤 1 中的 ObjectId 集合使用 Contains() 执行 Find()。

代码演示

public static class WidgetWorker
{
public static void Main()
{
//setup
var widgetCollection = new MongoClient("mongodb://localhost:27017")
.GetDatabase("WidgetDatabase")
.GetCollection<Widget>("Widget");
widgetCollection.DeleteManyAsync(x => true).Wait(); //remove all existing rows

//create widgets and add to DB; 2 SKUs, each with multiple revisions
var widgetA1 = new Widget() { SKU = "aaaa", Revision = 1M, Cost = 10 };
var widgetA2 = new Widget() { SKU = "aaaa", Revision = 2.1M, Cost = 20 };
var widgetA3 = new Widget() { SKU = "aaaa", Revision = 2.2M, Cost = 30 };
var widgetB1 = new Widget() { SKU = "bbbb", Revision = 1M, Cost = 40 };
var widgetB2 = new Widget() { SKU = "bbbb", Revision = 1.1M, Cost = 50 };
widgetCollection.InsertManyAsync(new[] { widgetA1, widgetA2, widgetA3, widgetB1, widgetB2 }).Wait();

//get the ObjectId of the most Recent revision of each SKU
var r = widgetCollection
.Aggregate()
.SortByDescending(x => x.Revision)
.Group(x => x.SKU, g => new { Id = g.First().Id })
.ToListAsync()
.Result;

//get the Widget objects for the list of ids just collected
var ids = r.Select(x => x.Id).ToArray();
var widgets = widgetCollection
.Find(x => ids.Contains(x.Id))
.ToListAsync()
.Result;

//check results
Debug.Assert(widgets.Count() == 2);
Debug.Assert(widgets.Single(x => x.SKU == "aaaa").Revision == 2.2M);
Debug.Assert(widgets.Single(x => x.SKU == "bbbb").Revision == 1.1M);
}
}

public class Widget
{
[BsonId]
public ObjectId Id { get; set; }
public string SKU { get; set; }
public decimal Revision { get; set; }
public decimal Cost { get; set; }
}

关于c# - Mongo C# Driver 2.0 聚合组异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30800050/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com