I would like to filter specific array elements out of a single document.
My goal is returning a "CustomEntity" object only including arrays in "CustomLog.Logs" where LogEntity.Data is "System.string"
public class CustomEntity
{
[BsonId]
public string Id { get; set; }
public LogEntity[] Logs { get; set; }
}
public class LogEntity
{
public string Data { get; set; }
public string DataType { get; set; }
}
My attempt:
Builders<CustomEntity>.Filter.ElemMatch(x => x.Logs,
Builders<LogEntity>.Filter.Eq(y => y.Data.DataType, "System.string"))
I tried to create some projections, but they just returned one array element (and i havnt got the code anymore..)
Any ideas?
CodePudding user response:
Issue & Concern
From this line:
Builders<LogEntity>.Filter.Eq(y => y.Data.DataType, "System.string")
This is incorrect as the Data
is a string and doesn't contain the field definition of DataType
.
Your filter query should be as below:
FilterDefinition<CustomEntity> filter = Builders<CustomEntity>.Filter.ElemMatch(x => x.Logs,
Builders<LogEntity>.Filter.Eq(y => y.DataType, "System.string"));
Solution