Home > Blockchain >  multiple search and filter data returning count of each filter in nestjs mongodb
multiple search and filter data returning count of each filter in nestjs mongodb

Time:10-30

I want to filter the items in the database by their fields and also return the count of each filter. Example is when I select to return specific brand names I want to see the number of brand name available.

Is there any search service I could use like Azure search or a way to implement this in NestJs and mongodb

This is the Database collection

{
  "brand": "Screaming Eagle, The Flight",
  "producer": "Screaming Eagle",
  "productionCountry": "America",
  "region": "Napa Valley",
  "appellation": "Oakville",
  "vintage": "2016",
  "grape": "Cabernet Sauvignon",
  "maturity": "25",
  "case": "3 bottles",
  "origin": "SECONDARYMARKET",
  "type": "Red"
},{
  "brand": "Joseph Phelps, Insignia",
  "producer": "Joseph Phelps",
  "productionCountry": "America",
  "region": "Napa Valley",
  "appellation": "St. Helena",
  "vintage": "2012",
  "grape": "Cabernet Sauvignon",
  "maturity": "25",
  "case": "6 bottles",
  "origin": "SECONDARYMARKET",
  "type": "Red"
},{
  "brand": "Joseph Phelps, Insignia",
  "producer": "Joseph Phelps",
  "productionCountry": "America",
  "region": "Napa Valley",
  "appellation": "St. Helena",
  "vintage": "2012",
  "grape": "Cabernet Sauvignon",
  "maturity": "25",
  "case": "6 bottles",
  "origin": "SECONDARYMARKET",
  "type": "Red"
},{
  "brand": "Continuum",
  "producer": "Continuum",
  "productionCountry": "America",
  "region": "Napa Valley",
  "appellation": "Oakville",
  "vintage": "2017",
  "grape": "Cabernet Sauvignon",
  "maturity": "26",
  "case": "6 bottles",
  "origin": "SECONDARYMARKET",
  "type": "Red"
},{
  "brand": "Continuum",
  "producer": "Continuum",
  "productionCountry": "America",
  "region": "Napa Valley",
  "appellation": "Oakville",
  "vintage": "2017",
  "grape": "Cabernet Sauvignon",
  "maturity": "26",
  "case": "6 bottles",
  "origin": "SECONDARYMARKET",
  "type": "Red"
}

CodePudding user response:

This is known as "facets" and it is supported by Azure Cognitive Search and MongoDB. In Azure Cognitive Search, you have to set facetable to true for the fields you'd like to get counts for, such as brand then specify in the query "facets": ["brand"].

For more information Azure Search see: https://learn.microsoft.com/en-us/azure/search/search-faceted-navigation

This works in MongoDb using the $facet aggregation operator which you can read more about here: https://www.mongodb.com/docs/manual/reference/operator/aggregation/facet/

  • Related