内容目录
1,一个字段是数组,如果数组中不存在这个记录时,向数组增加一个记录。
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);
首先是区配条件,找到这个根记录、数组中是否已经存在这个记录。
var f = fd.And(fd.Eq(x => x.Id, record.Id), fd.Not(fd.ElemMatch(x => x.Definition, x => x.Version == newVersionStr)));
然后通过 Push
,向数组推送一个记录。
up.Push(x => x.Definition, definition);
这样,并不需要提前查询数据库一次。
条件更新:
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();
}
文章评论