在数据库而不是内存中过滤集合
我有一个模型类,将其保存在MongoDB集合中,然后按照以下我的期望进行查询。
我的模特班:
public Class Employee
{
public ObjectId Id { get; set; }
public string EmpID { get; set; }
public string EmpName { get; set; }
public List<Mobile> EmpMobile { get; set; }
public bool IsLive { get; set; }
}
public Class Mobile
{
public string MobID { get; set; }
public string MobNumber { get; set; }
public bool IsPreferred { get; set; }
public bool IsLive { get; set; }
}
值是
List<Employee> EmpInfo = new List<Employee>() {
new Employee()
{
EmpID = "100",
EmpName = "John",
EmpMobile = new List<Mobile>()
{
new Mobile() { MobNumber = "55566610", IsPreferred = true, IsLive = false },
new Mobile() { MobNumber = "55566611", IsPreferred = false, IsLive = true },
},
IsLive = true
},
new Employee()
{
EmpID = "101",
EmpName = "Peter",
EmpMobile = new List<Mobile>()
{
new Mobile() { MobNumber = "55566610", IsPreferred = true, IsLive = false },
new Mobile() { MobNumber = "55566611", IsPreferred = false, IsLive = false },
},
IsLive = true
},
new Employee()
{
EmpID = "102",
EmpName = "Jack",
EmpMobile = new List<Mobile>()
{
new Mobile() { MobNumber = "55566610", IsPreferred = true, IsLive = true },
new Mobile() { MobNumber = "55566611", IsPreferred = false, IsLive = true },
},
IsLive = false
}
}
collectionEmpInfo.InsertMany(EmpInfo);
var empList = collectionEmpInfo.Find(new BsonDocument()).ToList();
现在,我希望仅EmpInfo.IsLive == true
在嵌入式文档中选择“我只需要EmpInfo.EmpMobile.IsLive == true
满足的移动文档”
我的预期输出:
List<Employee> EmpInfo = new List<Employee>() {
new Employee()
{
EmpID = "100",
EmpName = "John",
EmpMobile = new List<Mobile>()
{
new Mobile() { MobNumber = "55566611", IsPreferred = false, IsLive = true }
},
IsLive = true
},
new Employee()
{
EmpID = "101",
EmpName = "Peter",
EmpMobile = new List<Mobile>()
{
},
IsLive = true
}
}
请协助我如何使用c#MongoDB为期望的输出编写Where子句查询。
注意:在数据库而不是内存中过滤集合
我的MongoDB库和连接是
IMongoClient _client = new MongoClient();
IMongoDatabase _database = _client.GetDatabase("Test");
编辑
已添加projection
-因此所选数组仅包含文档,其中IsLive==true
我认为使用类型查询和使用c#
强类型语言比较容易。我使用ElemMatch
它的目的是扫描阵列并寻找匹配的元素。
var filterDef = new FilterDefinitionBuilder<Employee>();
var filter = filterDef.Eq(x => x.IsLive, true);
var projectDef = new ProjectionDefinitionBuilder<Employee>();
var projection = projectDef.ElemMatch<Mobile>("EmpMobile", "{IsLive:true}");
var empList = collectionEmpInfo.Find(filter).Project<Employee>(projection).ToList();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句