CodeMan CodeMan - 1 month ago 10
C# Question

MongoDb CSharp driver: Select rows where fieldX in set (val1,val2,val3)

var database = new MongoClient("mongodb://192.168.3.122").GetDatabase("TestDb");
var collection = database.GetCollection<Post>("Post");
var res = collection.AsQueryable().Where(x => x.Id.In(new List<int> { 1, 2, 3 })).Select(y => y).ToList(); //error here
foreach (var post in res)
{
Console.WriteLine(post.Id + " " + post.Code);
}


I want results similar to this SQL query:

Select * From Post Where Id In(1, 2, 3)

Answer

Try this

var Ids = new int[] { 1, 2, 3};
var res = collection.AsQueryable().Where(x => Ids.Contains(x.Id)).Select(y => y).ToList();