mongoDb和asp.net核心中的更新操作 [英] Update operation in mongoDb and asp.net core
问题描述
我是mongoDb的新手,并尝试使用mongoDb和Asp.net Core Web API进行CRUD操作. 我的问题是总是整个对象都更新了.我想更新在Web API中发送的特定字段.
I am new in mongoDb and try to do an CRUD operation using mongoDb and Asp.net Core web api. My problem is altime whole object becomes update. I want to update specific fields that I send in web api.
示例:
BusinessUnit oBU = new BusinessUnit(){
Id = "586e262268d90b290001b46e",
Name = "BU_Name",
Address = "my_Add"
};
现在,我只想将地址更新为"my_New_add",并要在下面创建对象:
Now I want to update only address to "my_New_add" and want to make below object :
BusinessUnit oBU = new BusinessUnit(){
Id = "586e262268d90b290001b46e",
Name = "BU_Name",
Address = "my_New_Add"
};
API调用: http://localhost:88786/api/BusinessUnit/586e262268d90b290001b46e
body:{"Id":"586e262268d90b290001b46e",地址":"my_New_add"}
body : {"Id" : "586e262268d90b290001b46e", "Address" : "my_New_add"}
但是所有时间它都会更新完整的对象.我该怎么解决?
But all time it updates full object. How can I solve it?
下面是我的代码:
控制器代码:
[HttpPut("{id}")]
public void Put(string id, [FromBody]BusinessUnit businessUnit)
{
_businessUnitRepository.UpdateBusinessUnit(id, businessUnit);
}
存储库代码:
public async Task<ReplaceOneResult> UpdateBusinessUnit(string id, BusinessUnit businessUnit)
{
return await _context.BusinessUnits.ReplaceOneAsync(doc => doc.Id == id, businessUnit);
}
实际上我想在下面进行查询(我知道mongodb是noSql,但是为了使我的问题更清楚,我在sql查询下面写了
Actually I want to do below query (I know mongodb is noSql, but for making my question clear I write below sql query)
UPDATE BusinessUnit设置地址="my_New_add",其中ID ="586e262268d90b290001b46e"
UPDATE BusinessUnit Set Address = "my_New_add" WHERE Id = "586e262268d90b290001b46e"
谢谢.
推荐答案
FindOneAndReplace
单个文档可以使用
FindOneAndReplace
或FindOneAndReplaceAsync
方法.
A single document can be replaced atomically using the
FindOneAndReplace
orFindOneAndReplaceAsync
methods.
var filter = new BsonDocument("FirstName", "Jack");
var update = Builders<BsonDocument>.Update.Set("FirstName", "John");
var result = collection.FindOneAndUpdate(filter, update);
if (result != null)
{
Assert(result["FirstName"] == "Jack");
}
以上内容将找到FirstName为Jack的文档,并将其FirstName字段设置为John.然后它将返回被替换的文档.
The above will find a document where the FirstName is Jack and set its FirstName field to John. It will then return the document that was replaced.
请参阅文档 查看全文