The LINQ query (which is covered by other answerers) works and is easier for those unfamiliar with the MongoDB Fluent query.
For those who are looking for MongoDB Fluent syntax:
Assume that your model classes are as below:
public class RootModel
{
[BsonId]
public int Id { get; set; }
public InfoModel[] Info { get; set; }
}
[BsonNoId]
public class InfoModel
{
public string Name { get; set; }
public string[] Random { get; set; }
}
You should work with .ElemMatch and .AnyIn:
var filter = Builders<RootModel>.Filter.ElemMatch(x => x.Info,
Builders<InfoModel>.Filter.Eq(y => y.Name, "John")
& Builders<InfoModel>.Filter.AnyIn(y => y.Random, new string[] { "31" }));
For the Post Owner's question on the differences between .In and .AnyIn:
In works when your field is a single value and is used to match any element from the provided input array.
AnyIn works when your field is an array and is used to match any element from the provided input array.
Based on your scenario, you will get the syntax error when using .In, for the implementation of In as below:
public FilterDefinition<TDocument> In<TField>(Expression<Func<TDocument, TField>> field, IEnumerable<TField> values)
{
return In(new ExpressionFieldDefinition<TDocument, TField>(field), values);
}
Unless you are checking the whole Random array that is exactly matched with the array, for example:
random: {
$in: [['31', 'food', 'sleep'], ...]
}
So this works with In:
Builders<InfoModel>.Filter.In(y => y.Random,
new string[][] { new string[] { "31", "food", "sleep" } })
That is another story matching the exact array value compared to the current question which asks for matching any element in the array.
info.random(and perhaps not even then - I've not really used Mongo text indexes).data.Where(x => x.info.Any(y => y.name == "John" && y.random.Any(z => z == "31")));should do the trick. Or if you meant the random strings contains 31 thendata.Where(x => x.info.Any(y => y.name == "John" && y.random.Any(z => z.Contains("31"))));should work.infofield always an array with a single object like shown (if so, why is it an array)?