内容目录
- A field is an array. If this record does not exist in the array, add a record to the array.
FilterDefinitionBuilder<WorkflowDo> fd = Builders<WorkflowDo>.Filter;
var f = fd.And(fd.Eq(x => x.Id, record.Id), fd.Not(fd.ElemMatch(x => x.Definition, x => x.Version == newVersionStr)));
UpdateDefinitionBuilder<WorkflowDo> up = Builders<WorkflowDo>.Update;
var p = up.Push(x => x.Definition, definition);
var result = await collection.UpdateOneAsync(f, p);
First, set the matching condition to find the root record and check if this record already exists in the array.
var f = fd.And(fd.Eq(x => x.Id, record.Id), fd.Not(fd.ElemMatch(x => x.Definition, x => x.Version == newVersionStr)));
Then, use Push
to add a record to the array.
up.Push(x => x.Definition, definition);
This way, there is no need to query the database in advance.
Conditional update:
public async Task<ServiceResult> SetStateAsync(ObjectId id, WorkflowInstanceStatus state)
{
var f = Builders<WorkflowInstanceDo>.Filter.Where(x => x.Id == id);
UpdateDefinitionBuilder<WorkflowInstanceDo> up = Builders<WorkflowInstanceDo>.Update;
var p = up.Set(x => x.Status, state);
var collection = _mongodb.GetCollection<WorkflowInstanceDo>();
var result = await collection.UpdateOneAsync(f, p);
return R.UpdateSuccess();
}
文章评论