Filter the Collection in DB instead of Memory
I'm having a Model Class, Save it in a MongoDB Collection then Query the same as per my expectation mentioned below.
My Model Class:
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; }
}
The Values are
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();
Now I wish to Select Only EmpInfo.IsLive == true
inside the embedded document I need only EmpInfo.EmpMobile.IsLive == true
satisfied Mobile documents
My Expected Output:
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
}
}
Kindly assist me how to write a Where Clause Query for my expected output using c# MongoDB.
Note: Filter the Collection in DB instead of Memory
My MongoDB Libraries and Connections are
IMongoClient _client = new MongoClient();
IMongoDatabase _database = _client.GetDatabase("Test");