Posts Tagged ‘C#

Remove by Id–MongoDB C#

When removing a document by the identifier using the C# 10gen driver for MongDB you need to specify the internally used id column, “_id”, not the property name from the DTO that you’re storing.

The Driver can be found on NuGet by search for MongoDB or the official project github page can be found here.

   1: public class DataProvider 

   2: { 

   3:     private MongoDatabase _db;

   4:     public DataProvider() 

   5:     { 

   6:         var server = MongoServer.Create("mongodb://127.0.0.1"); 

   7:         _db = server.GetDatabase("MyDB"); 

   8:     }

   9:     public void Delete(string id) 

  10:     { 

  11:         var collection = _db.GetCollection("MyDocumentCollection");

  12:         //Does not work 

  13:         //collection.Remove(new QueryDocument("Id", new BsonObjectId(id)));

  14:         //Works 

  15:         collection.Remove(new QueryDocument("_id", new BsonObjectId(id))); 

  16:     } 

  17: }

  18: public class MyDocument 

  19: { 

  20:     [BsonId] 

  21:     public ObjectId Id { get; set; } 

  22:     public string Name { get; set; } 

  23:     public string Description { get; set; } 

  24: }

 

I’ve submitted a pull request to have RemoveById added to the MongoCollection.

https://github.com/mongodb/mongo-csharp-driver/pull/87

Tags : ,