Improving MongoDB queries having $facet stage

I tested the following method:

Still having the same $facet stage, but until before, I have a $group subprocess to handle
SALE, FORECLOSURE, RENT, RENT_SALE and the exiting subprocess for MULTIOWER. So it looks like:

$facet:{
{
  res1:[{  $group:    {
  _id: null,
  SALE: {$sum: { $arrayElemAt: [ "$STATE", 0 ] }},
  FORECLOSURE: {$sum: { $arrayElemAt: [ "$STATE", 1 ] }},
  RENT: {$sum: { $arrayElemAt: [ "$STATE", 2 ] }},
}}],
MULTIOWER: [{$match: {{ $arrayElemAt: [ "$STATE", 0 ] }: 1 } }, {$group: {_id: '$OWNER_NAME', count: {$sum: 1 } } }, {$match: {count: {$gte: 2, $lte: 4 } } }, {$count: 'count'} ]
}
}

Now it’s faster than the first query, but may not be the ideal

1 Like