我有FileAggregateReport类:
public class FileAggregateReport
{
public Guid FileId { get; set; }
public Guid CorrelationId { get; set; }
public int NumberOfSupportedEngines { get; set; }
public int EnginesCompleted { get; set; }
public string SHA256 { get; set; }
public DateTime ScanDate { get; set; }
public List<EngineReport> EngineReports { get; set; }
}
我正试图将报告作为更新操作添加到列表中。
我的插入报告功能是:(
EngineReports
是FileAggregateReportCollection
)public void InsertNewEngineReport(Guid CorrelationId, Guid FileId, EngineReport engineReport, string sha256, int numberOfSupportedEngines)
{
var update = Builders<FileAggregateReport>.Update
.Inc(report => report.EnginesCompleted, 1)
.Set(report => report.CorrelationId, CorrelationId)
.Set(report => report.FileId, FileId)
.SetOnInsert(report => report.ScanDate, engineReport.ScanDate)
.SetOnInsert(report => report.SHA256, sha256)
.AddToSet( report => report.EngineReports, engineReport)
.Set(report => report.NumberOfSupportedEngines, numberOfSupportedEngines);
UpdateOptions options = new UpdateOptions { IsUpsert = true };
try
{
_mongoDbHelper.FileAggregateReportCollection.UpdateOne(e => e.FileId == FileId, update, options);
}
catch (Exception e)
{
throw new StateRepositoryException(e.Message);
}
}
}
当我这样做测试时:
Guid cor = Guid.NewGuid();
Guid fileID = Guid.NewGuid();
EngineReport report = new EngineReport()
{
FileId = fileID
};
_fileResultRepository.InsertNewEngineReport(cor, fileID, report, "dfsdfsdf", 15);
Task[] tasks = new Task[5];
for (int i = 0; i < 5; i++)
{
Task task = Task.Run(() =>
_fileResultRepository.InsertNewEngineReport(cor, fileID, new EngineReport()
{
FileId = fileID,
EngineType = EngineType.Clamav,
MaliciousScore = 70,
ScanDate = DateTime.Now,
ShortSummary = "ATD"
}, "dfsdfsdf", 5));
tasks[i]=task;
}
Task.WaitAll(tasks);
但在我的测试结果中,in
IMongoCollection<FileAggregateReport>
只有3个元素,需要6个元素。有时我得到了
EnginesReport
但我不能复制这个。 最佳答案
我在mongodb文档中看到了AddToSet
=>“除非值已经存在,$addtoset运算符将值添加到数组中,在这种情况下,$addtoset不会对该数组执行任何操作。”
我为Id
添加了新的FileAggregateReport
,因为FileId
与所有EngineReports
相同,在我的测试中更改后,我得到了6EngineReports
,如我所料。