In my mongodb, I have an array of objects that looks something like this.
[
{
_id: 123,
info: [
{
name: John,
random: ['31', 'food', 'sleep']
}
]
},
{
_id: 234,
info: [
{
name: Amy,
random: ['tv', 'food', 'sleep']
}
]
},
{
_id: 345,
info: [
{
name: John,
random: ['cars', 'tv31', 'sleep']
}
]
},
]
In C# how would I filter on info where name is John and random contains 31? I also don’t know what the difference is between the AnyIn vs In.
3
Answers
You should be able to query the
info
property of each data item to filter your results, something like:Following code works.
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:
You should work with
.ElemMatch
and.AnyIn
: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 ofIn
as below:Unless you are checking the whole
Random
array that is exactly matched with the array, for example:So this works with
In
:That is another story matching the exact array value compared to the current question which asks for matching any element in the array.