Search code examples
c#.netmongodbmongodb-querymongodb-.net-driver

How to convert a MongoDB query with "UnionWith" to C# MongoDB.Driver


I'm using .NET 8 And MongoDB.Driver 2.24 and I have the following model in 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; } 
}

I made query to find the first and the last record of MachineOperations based in the InsertedAt field:

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 } }
      ]
    }
  }
])

My problem is that I cant convert this query to C#. To be honest, I didn't find a single example of UnionWith in C#. All I got was this:

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

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

Which obviously doesn't work. Can anyone help me convert this query from MongoDB to C#?


Solution

  • Try the below:

        public class Projected
        {
            public DateTime InsertedAt { get; set; }
            public int MachineScheduleId { get; set; }
        }
    
        static void Main(string[] args)
        {
            var test = _collection
                .Aggregate()
                .SortBy(m => m.InsertedAt)
                .Limit(1)
                .Project(i => new Projected { InsertedAt = i.InsertedAt, MachineScheduleId = i.MachineScheduleId })
                .UnionWith(
                    _collection,
                    new EmptyPipelineDefinition<MachineOperation>()
                        .Sort(Builders<MachineOperation>.Sort.Descending(s => s.InsertedAt))
                        .Limit(1)
                        .Project(ii => new Projected { InsertedAt = ii.InsertedAt, MachineScheduleId = ii.MachineScheduleId }));
        }