我想知道如何使用 MongoDB 的 C# 驱动程序在数组中插入对象。
文件结构:
{
entity: {
identifier: 'id-001',
name: 'test-entity',
status: [
{
serviceName: 'service-1',
details: 'Processed by service-1'
},
{
serviceName: 'service-2',
details: 'Processed by service-2'
}
]
}
}
我认为这种方法可以完成工作:
public async Task SetStatusAsync(
string kind,
string identifier,
SynchronizationStatus syncStatus)
{
var collection = GetCollection(kind);
var update = Builders<Document>.Update.Combine(
Builders<Document>.Update.Set(x => x.Entity.Status[-1].ServiceName, syncStatus.ServiceName),
Builders<Document>.Update.Set(x => x.Entity.Status[-1].Details, syncStatus.Details));
var filter = Builders<Document>.Filter.And(
Builders<Document>.Filter.Eq(doc => doc.Entity.Identifier, identifier),
Builders<Document>.Filter.ElemMatch(x => x.Entity.Status, x => x.ServiceName == syncStatus.ServiceName));
var options = new FindOneAndUpdateOptions<Document>
{
IsUpsert = true
};
var result = await collection.FindOneAndUpdateAsync(filter, update, options);
return result.Entity;
}
...但是当给定实体的“状态”为空/空数组时,我收到以下错误:
位置运算符未从查询中找到所需的匹配项。
有什么建议吗?