Projection in Where Clause Query of a Embedded document in MongoDB Collection using C#

前端 未结 3 716
悲&欢浪女
悲&欢浪女 2021-01-23 10:00

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 expec

3条回答
  •  太阳男子
    2021-01-23 10:22

    You have several int for your approach.

    first you are using collectionEmpInfo.InsertOne(EmpInfo); i am assuming you want to use InsertMany instead.

    as for filtering over the collection you have to know that your filter will affect if the whole object is retrieved, so adding a filter on an embedded array within an entity will not filter the array but determine if the whole object is retrieved or not based on whether it matches the query condition on the embedded array. My suggestion is to only apply the filter over the employees in the query and filter the result set in memory.

    var filter = filterBuilder.Eq("IsLive", true);
    
    var results = await collection.FindAsync(filter).ToListAsync();
    

    now filter the results collection in memory as in

    var filteredResults = results.ForEach(employee => employee.EmpMobile = employee.EmpMobile.Where(mob => mob.isLive).ToList());
    

提交回复
热议问题