Danny
Danny

Reputation: 179

Can list of IDs(string) be passed to a delete method for MongoDB?

I have a list of Ids that need to be deleted. I'm getting my collection from the database and passing it a resource. From which I want to iterate through the collection and delete a list of Ids being passed.

Before I was deleting records with a filter but I no longer need to search for Id as I am now passing a list of Ids.

public Task<DataRetentionOperationResult> 
DeleteIdentifiedDataAsync(List<String> Ids, String Resource, 
CancellationToken cancellationToken = default)
    {
        var collection = _db.GetCollection<BsonDocument>(Resource);

        foreach (var id in Ids)
        {                
            collection.DeleteManyAsync<BsonDocument>(id, cancellationToken);
        }

        throw new NotImplementedException();
    }

I expect for the documents associated with the Ids passed to be deleted.

Upvotes: 0

Views: 368

Answers (1)

mickl
mickl

Reputation: 49985

To remove multiple documents you can build a filtering condition based on Ids using $in operator. Please remember about awaiting Async functions,

var filter = Builders<BsonDocument>.Filter.In(f => f["_id"], Ids);
await collection.DeleteManyAsync(filter);

Upvotes: 2

Related Questions