Search code examples
mongodbmongodb-.net-driver

Delete multiple documents using MongoDB driver doesn't work


I am trying to delete multiple documents in MongoDB using MongoDB.Driver with vb.net. However, it doesn't work and gives the error:

'Unable to cast object of type 
'MongoDB.Driver.SimpleFilterDefinition`2[MongoDB.Bson.BsonDocument,System.String]' 
to type 'MongoDB.Driver.IClientSessionHandle'.'

The code is as follows:

Public Function DeleteAllContent(item As Content) As String
   Dim db As IMongoDatabase = DatabaseService.GetDBcontext()
   Dim filterId = Builders(Of BsonDocument).Filter.Eq(Of String)(("id"), item.ID)
   Dim filterResourceId = Builders(Of BsonDocument).Filter.Eq(Of String)(("resourceId"), item.ID)

   db.GetCollection(Of BsonDocument)("Contents").DeleteMany(filterId, filterResourceId) <<exception here

   Return String.Empty
End Function

Tried the followings but didn't work

1.

 Dim db As IMongoDatabase = DatabaseService.GetDBcontext()
 Dim filterResourceId = Builders(Of BsonDocument).Filter.Eq(Of String)(("resourceId"), item.ID)

 db.GetCollection(Of BsonDocument)("Contents").DeleteMany(filterResourceId)
  1. From here

        Dim db As IMongoDatabase = DatabaseService.GetDBcontext()
        Dim filterResourceId = Builders(Of BsonDocument).Filter.Eq(Of String)(("resourceId"), item.ID)
        Dim result = db.GetCollection(Of BsonDocument)("Cards").Find(filterResourceId).ToList
        Dim extractedIds = result.Select(Of BsonDocument)(Function(x) x("id").ToString()).ToList()
        Dim deleteList = Builders(Of BsonDocument).Filter.In(Of String)("id", extractedIds)
    
        db.GetCollection(Of BsonDocument)("Cards").DeleteMany(deleteList)
    

Solution: DeleteMany doesn't take multiple filters. So that needs to be combined. The following code worked.

 Dim filterResourceId = Builders(Of BsonDocument).Filter.Eq(Of String)(("resourceId"), item.ID)

 db.GetCollection(Of BsonDocument)("Contents").DeleteMany(filterResourceId)

Solution

  • there is no overload for DeleteMany that takes two filters as parameters, so since the best-matched overload is (IClientSessionHandle session, FilterDefinition<TDocument> filter..) (c#), the error says that the provided filter (filterId) cannot be converted to IClientSessionHandle). So you just use it in the wrong way, you should create a single filter that will include any conditions you need