How to remove one 'document' by 'ID' using the Official C# Driver for MongoDB?

匆匆过客 提交于 2019-11-29 02:57:33

That's the way you do it. I'm sure you know this, but if you want to put it on one line you could combine it so you don't need to define a query variable:

collection.Remove(Query.EQ("_id", a.Id));

If the [id] is string, you must use ObjectId instance explicitly.

var query = Query.EQ("_id", ObjectId.Parse(id));

The Simplest Way

Remove a document from a collection for C# MongoDB Driver (v2.0 or later)-

collection.DeleteOne(a => a.Id==id);

Or-

await collection.DeleteOneAsync(a => a.Id==id);

My ASP.NET Core MVC controller's action accepts Id as a string parameter. Then I parse it and use the result in the DeleteOne() statement:

[HttpPost]
public IActionResult Delete(string id)
{
    ObjectId objectId = ObjectId.Parse(id);
    DbContext.Users.DeleteOne(x => x.Id == objectId);
    return null;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!