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

后端 未结 5 1247
萌比男神i
萌比男神i 2020-12-10 01:09

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

va         


        
相关标签:
5条回答
  • 2020-12-10 01:22

    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);
    
    0 讨论(0)
  • 2020-12-10 01:28
    var filter = Builders<BsonDocument>.Filter.Eq("_id",ObjectId.Parse(id));
    var x = data.DeleteOne(filter);
    

    I am using this with the current version ( in 2019 ), and it works.

    0 讨论(0)
  • 2020-12-10 01:34

    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;
    }
    
    0 讨论(0)
  • 2020-12-10 01:38

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

    var query = Query.EQ("_id", ObjectId.Parse(id));
    
    0 讨论(0)
  • 2020-12-10 01:44

    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));
    
    0 讨论(0)
提交回复
热议问题