Home > Enterprise >  MongoDB C# 2.14 Driver Filter.In
MongoDB C# 2.14 Driver Filter.In

Time:11-27

I am trying to get all documents where the document's array field has matched values using Filter.In API.

Filter.In method requires FieldDefinition and values array, but if I am using lambda, that doesn't work.

Is it indented this way or I am facing some kind of bug?

I am trying a strongly typed approach.

genres = new[] {"one", "two", "three"};
//This filter works
var filter = Builders<Movie>.Filter
    .ElemMatch(movie => movie.Genres, genre => genres.Contains(genre));
//This filter works
var filter2 = Builders<Movie>.Filter.In(nameof(Movie.Genres), genres);
//This filter works
var filter3 = Builders<Movie>.Filter.In("genres", genres);
//Doesn't compile
var filter4 = Builders<Movie>.Filter.In(movie => movie.Genres, genres);

CodePudding user response:

In filter checks whether value of the specified field is contained in the provided array. You could use this filter if you had a single Genre associated with a movie. You get that compile time error because filter builder expects this field to be of type string and not string[].

To check whether your array field contains a value from the provided array, try this:

var filter = Builders<Movie>.Filter.AnyIn(movie => movie.Genres, genres);
  • Related