Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm not sure if this is a possible solution, but what if you begin the aggregation process by determining the number of different locations using distinct(), and run separate aggregation commands for each location? distinct() may not be efficient, but every subsequent aggregation will be able to use $match, and therefore, the index on categories. You could use the same logic to count the fruit for "categories.type".</p> <pre><code>{ "_id" : 1, "house" : "New York", "people" : { "John" : [{"k" : "apples","v" : 1},{"k" : "oranges","v" : 2}], "Dave" : [{"k" : "apples","v" : 2},{"k" : "oranges","v" : 1}] }, "categories" : [{"location" : "central"},{"type" : "rented"}] } { "_id" : 2, "house" : "London", "people" : { "John" : [{"k" : "apples","v" : 3},{"k" : "oranges","v" : 2}], "Dave" : [{"k" : "apples","v" : 3},{"k" : "oranges","v" : 1}] }, "categories" : [{"location" : "suburb"},{"type" : "rented"}] } { "_id" : 3, "house" : "London", "people" : { "John" : [{"k" : "apples","v" : 0},{"k" : "oranges","v" : 1}], "Dave" : [{"k" : "apples","v" : 2},{"k" : "oranges","v" : 4}] }, "categories" : [{"location" : "central"},{"type" : "rented"}] } </code></pre> <p>Run distinct() and iterate through the results by running aggregate() commands for each unique value of "categories.location":</p> <pre><code>db.agg.distinct("categories.location") [ "central", "suburb" ] db.agg.aggregate( {$match: {categories: {location:"central"}}}, //the index entry is on the entire {$unwind: "$people.John"}, //document {location:"central"}, so {$group:{ //use this syntax to use the index _id:"$people.John.k", "numberOf": { $sum: 1 }, "Total Fruit": { $sum: "$people.John.v"} } } ) { "result" : [ { "_id" : "oranges", "numberOf" : 2, "Total Fruit" : 3 }, { "_id" : "apples", "numberOf" : 2, "Total Fruit" : 1 } ], "ok" : 1 } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload