如何使用 MongoDB 的官方 C# 驱动程序通过“ID”删除一个“文档”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8867032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:52:28  来源:igfitidea点击:

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

c#.netmongodbmongodb-.net-driver

提问by Travis Laborde

Can someone please show me, if there is a better way to remove one documentfrom MongoDB using the Official C# Driverthan what I have below-

是否有人可以告诉我,如果有更好的方法来删除一个document使用MongoDB的来自官方的C#司机比我有如下─

var query = Query.EQ("_id", a.Id);
database.GetCollection<Animal>("Animal").Remove(query);

This code works, but seems too much workto me. The "Save" command for example- takes an instance and updates it. I want something like- Remove(item).

这段代码有效,但对我来说似乎工作太多了。例如,“保存”命令 - 获取一个实例并更新它。我想要类似 - 的东西Remove(item)

Remarks:I'm trying to use the official driver of C# rather than NoRMor Samuswhich seems out of date.

备注:我正在尝试使用 C# 的官方驱动程序,而不是似乎过时的NoRMSamus

采纳答案by Eve Freeman

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));

回答by Ostati

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

如果 [id] 是字符串,则必须显式使用 ObjectId 实例。

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

回答by Minhas Kamal

The Simplest Way

最简单的方法

Remove a documentfrom a collectionfor C# MongoDB Driver(v2.0 or later)-

删除document从一个collectionC#MongoDB的驱动程序(2.0版或更高版本) -

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

Or-

或者-

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

回答by Aleksei Mialkin

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:

我的 ASP.NET Core MVC 控制器的操作接受 Id 作为字符串参数。然后我解析它并在 DeleteOne() 语句中使用结果:

[HttpPost]
public IActionResult Delete(string id)
{
    ObjectId objectId = ObjectId.Parse(id);
    DbContext.Users.DeleteOne(x => x.Id == objectId);
    return null;
}