Filter the collection in the database instead of memory
I have a model class, save it in the MongoDB collection, then request the same as in 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; } }
Values
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 want to select only EmpInfo.IsLive == true inside the embedded document I only need EmpInfo.EmpMobile.IsLive == true modified mobile documents
My expected result:
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 } }
Please help me write a Where Clause query for my expected output using C # MongoDB .
Note: Filter the collection in the database instead of memory
My libraries and MongoDB connections
IMongoClient _client = new MongoClient(); IMongoDatabase _database = _client.GetDatabase("Test");