Dreyser Eguia
Dreyser Eguia

Reputation: 438

Linq filter builder not accepting lambda for filter type IN

Basically what I'm trying to do is a deleteMany based on a list of items that I have using C# and linq for a mongoDB.

This is my code:

// List of elements to delete, read from the POST request   
string jsonBoletines = await new StreamReader(req.Body).ReadToEndAsync();

// Convert the JSON into a list of "Boletin" objects, which is the type of objects I want //to delete from the collection 
List <Boletin> boletinesToDelete = JsonConvert.DeserializeObject<List<Boletin>>(jsonBoletines);

// Create the filter using IN, I'm trying to delete using the _id
var filter = Builders<Boletin>.Filter.In(item => item._id, boletinesToDelete);

var results = collection.DeleteMany(filter);

My code will not compile because on the lambda inside the IN filter shows this error:

var filter = Builders<Boletin>.Filter.In(item => item._id, boletinesToDelete);

CS1660: Cannot convert lambda expression to type X because it is not a delegate type

Did some research and the error is supposed to be "This error occurs if you try to assign or otherwise convert an anonymous method block to a type which is not a delegate type". But I'm not sure I get it since I'm not that familiar with delegate type

Please help

Upvotes: 0

Views: 251

Answers (3)

Dreyser Eguia
Dreyser Eguia

Reputation: 438

Not sure if it´s the best way to solve it, but it´s the way it worked for me

// read the contents of the POST body data into a string
   string listBoletines = await new StreamReader(req.Body).ReadToEndAsync();
            
// listBoletines is a list of string IDs, so need to convert to ObjectId
    
//Fist create an array with each ID
string [] boletinesToDelete = listBoletines.Split(',');

//Create a second array of type ObjectId 
ObjectId[] idsToDelete = new ObjectId[boletinesToDelete.Length];

//For each string on first array create it's corresponding ObjectId and insert on second array
for (int i=0; i<boletinesToDelete.Length; i++)
 {
    idsToDelete[i] = new ObjectId(boletinesToDelete[i]);
 }
 
//Finally I an use that in the filter against a MongoDB _id   
 var filter = Builders<Boletin>.Filter.In("_id", idsToDelete);
 var results = collection.DeleteMany(filter);

Upvotes: 0

YuTing
YuTing

Reputation: 6629

boletinesToDelete should be a List<ObjectId> or a List<string> according to your item._id not a List<Boletin>.

db.collection.find({
  _id: {
    "$in": [
      ObjectId("5a934e000102030405000000"),
      ObjectId("5a934e000102030405000001")
    ]
  }
})

mongoplayground

Upvotes: 0

joshman1019
joshman1019

Reputation: 159

From memory, I think an intersect may work better for this.

var filter =  Builders<Boletin>.Intersect(boletinesToDelete);

Upvotes: 0

Related Questions