我尝试在MongoDb中更新或插入文档:
return Collection.UpdateOneAsync(x => x.UserId == document.UserId,
document.GetUpdateDefinition(),
new UpdateOptions() { IsUpsert = true });
我在更新定义中也包含UserId
,因为它是insert
并且文档不存在:
public UpdateDefinition<UserModel> GetUpdateDefinition()
{
return Builders<UserModel>.Update
.Set(nameof(UserId), UserId)
.Set(nameof(FirstName), FirstName)
.Set(nameof(LastName), LastName)
}
但有时我会收到此错误:
E11000 duplicate key error collection: Data index: _id_ dup key: { : "3232333" }
如何解决此错误?感谢。
更新 这是我的模特:
public class UserModel
{
[BsonId]
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}