我想要实现的是为该方法提供List<JobList>
包含作业的客户端 ID 和 InternalIds 。Finish()
然后我想遍历客户端并更新所有与 JobInternalIds 匹配的作业并将当前日期时间设置为 FinishedAt 字段。问题是我完全不知道如何更新嵌套对象。
我尝试过类似下面的方法,但没有成功。
public class Client
{
[BsonId]
public ObjectId Id { get; set;}
public string Name { get; set;}
public List<Job> Jobs { get; set;}
}
public class Job
{
public string InternalId { get; set;}
public string Name { get; set;}
public DateTime? FinishedAt { get; set;}
}
public class JobList
{
public string ClientId { get; set; }
List<string> JobInternalIds { get; set; }
}
public async Task Finish(List<JobList> joblist)
{
var updateDefinition = new UpdateDefinitionBuilder<Client>()
.Set(x => x.Job[0].FinishedAt, DateTime.UtcNow); // don't know how to set datetime to finishedAt for each elements of collection that matches InternalIds
foreach(var item in joblist)
{
await _db.Collection.UpdateManyAsync(item.ClientId, updateDefinition);
}
}
----------EDITED----------
public async Task Finish(List<JobList> joblist)
{
var updateDefinition = Builders<Client>.Update
.Set(x => x.Jobs[-1].FinishedAt, DateTime.UtcNow);
foreach (var item in joblist)
{
var internalIds = item.JobInternalIds.Select(x => x.InternalId).ToList();
var idFilter = Builders<Client>.Filter.Eq(x => x.Id, item.ClientId);
var internalIdsFilter = Builders<Client>.Filter.ElemMatch(x => x.Jobs, y => internalIds.Contains(y.InternalId));
var combinedFilters = Builders<Client>.Filter.And(idFilter, internalIdsFilter);
await _db.Collection.UpdateManyAsync(combinedFilters, updateDefinition);
}
}