Remove objects from an mongoDB Array

mongoDB Collection

{
    "_id" : ObjectId("58d0e87a0fa052d188424bc7"),
    "_CompanyID" : BinData(3, "+4IlRPd+6UmiuIJ7sNHwfQ=="),
    "CompanyName" : "dprsales7200",
    "CustomRoles" : [
        {
            "RoleId" : NumberInt(3),
            "Name" : "ss"
        },
        {
            "RoleId" : NumberInt(4),
            "Name" : "sssdd"
        }
    ]
    }
}

Q. I want to remove a Custom Role from the CustomRoles array which matches the RoleID.

C# Solution

public async Task<byte> deleteCustomRoleToCompany(Guid companyId, IdentityUserRole role)
        {
            var companyCollection = dbRepo.GetDbCollection().GetCollection<CompanyModel>(DBColletions.CollectionComapny);
            var removeFilter = Builders<CompanyModel>.Update.PullFilter(c => c.CustomRoles, f => f.RoleId == role.RoleId);
            await companyCollection.FindOneAndUpdateAsync(c => c._CompanyID == companyId, removeFilter);
            return 1;
        }

Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#