met*_*ase 5 c# mongodb aggregation-framework mongodb-.net-driver
我使用 MongoDB 的 Compass 创建了一个导出到 C# 的管道,但是我不确定如何在实际代码中使用它(工具生成 BsonArray)来执行聚合?这是 LINQ 目前不支持的 geoNear(如果有任何方位的话)。
我尝试使用一些文档var result = collection.Aggregate(pipeline);建议的(管道 - 是 Compass 生成的 BsonArray 对象)。
指南针将创建的示例:
new BsonArray
{
new BsonDocument("$geoNear",
new BsonDocument
{
{ "near",
new BsonDocument
{
{ "type", "Point" },
{ "coordinates",
new BsonArray
{
-2.11,
52.55
} }
} },
{ "distanceField", "distanceField" },
{ "maxDistance", 5000 },
{ "spherical", true }
}),
new BsonDocument("$sort",
new BsonDocument("distanceField", -1))
};
Run Code Online (Sandbox Code Playgroud)
事实证明,使用指南针生成的代码只需要强类型化即可。由于某种原因,编译器无法解释正在发生的事情(与原始代码的想法相反。因此不需要使用 var 而是需要类型。现在看起来很微不足道......
举个例子:
PipelineDefinition<Transport, Transport> pipeline= new BsonArray
{
new BsonDocument("$geoNear",
new BsonDocument
{
{ "near",
new BsonDocument
{
{ "type", "Point" },
{ "coordinates",
new BsonArray
{
-2.11,
52.55
} }
} },
{ "distanceField", "distanceField" },
{ "maxDistance", 5000 },
{ "spherical", true }
}),
new BsonDocument("$sort",
new BsonDocument("distanceField", -1))
};
//this will now work
var cursor = await collection.AggregateAsync(pipeline);
var listResult = await cursor.ToListAsync();
Run Code Online (Sandbox Code Playgroud)