DalekSall DalekSall - 10 months ago 81
ASP.NET (C#) Question

MongoDB and .NET: Filter on specific field in child array using FilterDefinition

I have a class which creates a list of filters from an input.
The filters are found by calling a function for each filter like this:

public void created_after(string date)
DateTime convertedDate = Convert.ToDateTime(date);
filters.Add(Builders<User>.Filter.Gte(x => x.Created, convertedDate));

Now i need to segment on a field on a child array on the user.
In this case, i just need to know if any alert has a Created value higher than a given date.
My data looks like this:

"DisplayName" : "PestisanRadu",
"Alerts" : [
"UserId" : ObjectId("577a26a12b365917c4d67dd5"),
"Created" : ISODate("2016-10-05T09:17:44.382+0000")
"UserId" : ObjectId("577a26a82b365917c4d68009"),
"Created" : ISODate("2016-10-05T18:44:45.743+0000")
"Created" : ISODate("2016-10-05T09:17:43.423+0000")

For the class to work, i need to keep the FilterDefinition type.

Answer Source

Use other same method which take FieldDefinition as parameter, in your case would be

filters.Add(Builders<User>.Filter.Gt("Alerts.Created", convertedDate));

Note that the string "Alerts.Created" is FieldDefinition