2

I am trying to delete the document by id, which is of type ObjectId, I do have converted the string to ObjectId and passed as parameter to remove from collection, but I am not able to delete the record.

I don't know what is the actuall reason behind, Looking for solution, below is my code sample:

 public void DeleteRecords(string objectID)
        {
            try
            {
                // Create server settings to pass connection string, timeout, etc.
                MongoServerSettings settings = new MongoServerSettings();
                settings.Server = new MongoServerAddress("localhost", 27017);
                // Create server object to communicate with our server
                MongoServer server = new MongoServer(settings);

                MongoDatabase myDB = server.GetDatabase("DemoMongoDB");

                MongoCollection<BsonDocument> records = myDB.GetCollection<BsonDocument>("Records");
                //var query = Query<Records>.EQ(fd => fd._id, ObjectId.Parse(name));
                var query = Query<Records>.EQ(e => e._id, new BsonObjectId(objectID));
                records.Remove(query);

            }
            catch (Exception ex)
            {

            }
        }
Systematix Infotech
  • 2,345
  • 1
  • 14
  • 31
  • Raise any exception? If so, please post the exception here – Peyman Apr 09 '15 at 06:40
  • The code works all good, without any exception, but document does not get deleted. – Systematix Infotech Apr 09 '15 at 06:47
  • 1
    possible duplicate of [how to remove one document by Id using the official CSharp driver for Mongo](http://stackoverflow.com/questions/8867032/how-to-remove-one-document-by-id-using-the-official-csharp-driver-for-mongo) – Anton Putau Sep 22 '15 at 23:53

2 Answers2

3

Try below code, and see whether is working?

var query = Query.EQ("_id", new BsonObjectId("objectID"));

Or

var query = Query.EQ("_id", name);
records.Remove(query);
Peyman
  • 3,068
  • 1
  • 18
  • 32
0

Finally, This worked for me, without converting the string to object id and pass as a parameter as a string itself.

var query = Query.EQ("_id", objectID);
records.Remove(query);
Systematix Infotech
  • 2,345
  • 1
  • 14
  • 31