我正在使用 .NET 8 和 MongoDB.Driver 2.24 并且我在 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; }
}
我查询以基于
MachineOperations
字段查找 InsertedAt
的第一条和最后一条记录:
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#。说实话,我在 C# 中没有找到任何
UnionWith
的例子。我得到的只是这个:
var collection = database.GetCollection<MachineOperation>("MachineOperation");
var test = _collection
.Aggregate()
.SortBy(m => m.InsertedAt)
.Limit(1)
.UnionWith(_collection)
.SortByDescending(m => m.InsertedAt)
.Limit(1);
这显然行不通。谁能帮我将此查询从 MongoDB 转换为 C# 吗?
尝试以下方法:
public class Projected
{
public DateTime InsertedAt { get; set; }
public int MachineScheduleId { get; set; }
}
static void Main(string[] args)
{
var client = new MongoClient();
var db = client.GetDatabase("db");
var _collection = db.GetCollection<MachineOperation>("c");
var test = _collection
.Aggregate()
.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}))
.SortByDescending(m => m.InsertedAt)
.Limit(1);
}