我正在尝试使用 MongoDB.Driver
和 vb.net
删除 MongoDB 中的多个文档。但是,它不起作用并给出错误:
'Unable to cast object of type
'MongoDB.Driver.SimpleFilterDefinition`2[MongoDB.Bson.BsonDocument,System.String]'
to type 'MongoDB.Driver.IClientSessionHandle'.'
代码如下:
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
尝试了以下方法但没有用
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)
来自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)
解决方案: DeleteMany
不采用多个过滤器。所以这需要结合起来。以下代码有效。
Dim filterResourceId = Builders(Of BsonDocument).Filter.Eq(Of String)(("resourceId"), item.ID)
db.GetCollection(Of BsonDocument)("Contents").DeleteMany(filterResourceId)
答案 0 :(得分:0)
DeleteMany 没有以两个过滤器作为参数的重载,因此由于最佳匹配的重载是 (IClientSessionHandle session, FilterDefinition<TDocument> filter..) (c#)
,错误表明提供的过滤器 (filterId
) 无法转换为 IClientSessionHandle) .所以你只是以错误的方式使用它,你应该创建一个包含你需要的任何条件的过滤器