MongoDB how to do multiple aggregations in one query with C# driver?

Viewed 642

My data model looks something like this:

{
    "ListingId": 1,
    "Status": "Current",
    "Category": "Rental"
}

I have around 5 million documents, and would like to run aggregations on both the "status" and "category" fields, so i can produce an output like this:

{
   "Statuses": 
   {
      "Current": 100, // count of all documents with 'Status' = 'Current'
      "Sold": 12 // count of all documents with 'Status' = 'Sold'
      // etc
   },
   "Categories": 
   {
      "Sale": 120,
      "Rental": 12
      // etc
   }
}

Basically, i want to return data to power a 'faceted search' UI, so i need the count's of all facets, and I want to do it in one trip to MongoDB.

I've been reading up about Aggregations and Facets for a day or so now, and i'm still confused.

Questions:

  1. Given my scenario and collection size, what should i be using here? Facets or Aggregations?
  2. How do i do it in the latest C# driver?

Related questions (which i haven't been able to convert to my situation / code):

1 Answers

You can get these data in a little bit different way with aggregation like below. Try facet code like below in my screenshot. Let me know if more help is required.

Faceted Result

You can export the same pipeline and put it in your c# code.

Related