It's well know that, we have filter and project definition builders in MongoDB .NET Driver API. We always filter our data in the filter definition and project the required fields with project definition. Wait! Is it possible to do a second level of filter inside a project definition? Of course, it is!
So here I take you to see how to implement filter inside a project definition.
Let's assume a MongoDB collection with structure below:
Sample Document:
{
_id:"CS-1001",
shopCategory:"Coffee",
shopName:"Your Regional Café",
qualityRate:"High",
branches:[
{address:"123, xxxxx, yyyy, zzzz", qualityRate:"High",openHours:["7.00 - 12.30", "14.00 - 20.00"]},
{address:"009, yyyyy, xxxxx, zzzz", qualityRate:"Mid",openHours:["7.00 - 12.00", "13.00 - 19.30"]}
],
menu: [
{type: "Espresso", price:{small:75.00, medium: null, large:115.00}},
{type: "Latte", price:{small:100.00, medium: null, large:145.00}},
{type: "Mocha", price:{small:145.00, medium: null, large:180.00}},
{type: "Kesar Cappuccino", price:{small:145.00, medium: null, large:180.00}},
{type: "Caramel Cappuccino", price:{small:145.00, medium: null, large:180.00}},
{type: "Americano", price:{small:91.00, medium: null, large:115.00}}
],
contact:{
phone:"00-00000", eMail: "xxyy@zz"
},
owner:{
name:"xyz yzx", blog:"zzzzz@yyy.xxx"
},
launchDate: "2000-05-01T06:30:02Z",
availableServices: ["Online Order", "Discounts", "Free Delivery"],
availableOffer: " +100 points to the credit wallet for customers visiting Café with their kitty🐈"
}
Imagine there is a requirement to display the list of Coffee Shops with only High ratings.
Now let's build the filter and project definitions for the above requirement:
Filter Definition:
var filter = Builders<docModel>.Filter.Eq(x=>x.shopCategory == "Coffee") &
Builders<docModel>.Filter.Eq(x=>x.qualityRate == "High");
Project Definition:
var project = Builders<docModel>.Projection.Expression(x=> new docModel
{
shopName = x.shopName,
branches = x.branches.Where(y => y.qualityRate == "High").ToArray(),
qualityRate = x.qualityRate,
menu = x.menu,
contact = x.contact,
availableServices = x.availableServices,
availableOffer = x.availableOffer
};
The above filter definition filters only - Coffee shops with High quality rating. The project definition projects the required fields but not limited to filter.
As we can see the sample document from the MongoDB collection, there is a field called branches which is an object array.
With the above filter definition we can only filter out the Coffee shops with common High quality rating. But as we can see every branches of the coffee shops has it's own quality rating.
Hence we need a second level of filter to provide the best result.
To achieve this, we have used the Expression method which creates the projection based on the expression Where(y => y.qualityRate == "High").
Comments
Post a Comment