You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含UnionWith的MongoDB查询转换为C# MongoDB.Driver代码

解决MongoDB聚合查询(UnionWith)的C#转换问题

模型定义

public class MachineOperation
{
    public int TotalProduction { get; set; }
    public int TotalBad { get; set; }
    public int TotalWhite { get; set; }
    public DateTime InsertedAt { get; set; }
    public int MachineScheduleId { get; set; } 
}

原始MongoDB聚合查询

db.MachineOperation.aggregate([
  {
    "$sort": {
      "InsertedAt": 1
    }
  },
  {
    $limit: 1
  },
  { $project : { InsertedAt : 1, MachineScheduleId : 1 } },
  {
    "$unionWith": {
      "coll": "MachineOperation",
      "pipeline": [
        {
          "$sort": {
            "InsertedAt": -1
          }
        },
        {
          $limit: 1
        },
        { $project : { InsertedAt : 1, MachineScheduleId : 1 } }
      ]
    }
  }
])

错误的C#尝试代码

var collection = database.GetCollection<MachineOperation>("MachineOperation");

var test = _collection
    .Aggregate()
    .SortBy(m => m.InsertedAt)
    .Limit(1)
    .UnionWith(_collection)
    .SortByDescending(m => m.InsertedAt)
    .Limit(1);

正确的C#转换代码

你之前的写法错误在于:UnionWith需要接收一个完整的聚合管道定义,而不是直接链式调用后续的排序、限制操作。正确的写法需要为UnionWith单独定义第二个查询的管道,同时要添加投影操作来匹配原始查询只返回指定字段的逻辑:

拆分管道写法

var collection = database.GetCollection<MachineOperation>("MachineOperation");

// 获取最早的记录:按InsertedAt升序取第一条,仅返回指定字段
var earliestPipeline = collection.Aggregate()
    .SortBy(m => m.InsertedAt)
    .Limit(1)
    .Project(m => new { m.InsertedAt, m.MachineScheduleId });

// 获取最晚的记录:按InsertedAt降序取第一条,仅返回指定字段
var latestPipeline = collection.Aggregate()
    .SortByDescending(m => m.InsertedAt)
    .Limit(1)
    .Project(m => new { m.InsertedAt, m.MachineScheduleId });

// 合并两个管道的结果
var result = earliestPipeline.UnionWith(latestPipeline).ToList();

紧凑链式写法

var collection = database.GetCollection<MachineOperation>("MachineOperation");

var result = collection.Aggregate()
    .SortBy(m => m.InsertedAt)
    .Limit(1)
    .Project(m => new { m.InsertedAt, m.MachineScheduleId })
    .UnionWith(
        collection.Aggregate()
            .SortByDescending(m => m.InsertedAt)
            .Limit(1)
            .Project(m => new { m.InsertedAt, m.MachineScheduleId })
    )
    .ToList();

关键点说明

  • UnionWith的参数必须是另一个IAggregateFluent<T>对象,即完整的聚合管道,不能直接在其后链式调用排序、限制等操作。
  • 使用Project方法筛选返回字段,对应原始MongoDB查询中的$project阶段,避免返回不必要的字段。
  • 最后调用ToList()执行查询并获取结果集合。

内容的提问来源于stack exchange,提问作者guirms

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 20:07:30