[SERVER-23654] Add $facet aggregation stage Created: 12/Apr/16  Updated: 03/Aug/20  Resolved: 24/Jun/16

Status: Closed
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: None
Fix Version/s: 3.3.9

Type: New Feature Priority: Major - P3
Reporter: Charlie Swanson Assignee: Charlie Swanson
Resolution: Done Votes: 0
Labels: stage
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Depends
is depended on by CSHARP-1715 Add support for $facet aggregation stage Closed
is depended on by JAVA-2255 Add builder for $facet aggregation stage Closed
Documented
is documented by DOCS-8830 Faceted Search - $facet Closed
Duplicate
is duplicated by SERVER-15611 Support returning both the matched do... Closed
Related
is related to SERVER-12927 Support ROLLUP function in the $group... Backlog
is related to DRIVERS-297 Aggregation Framework Support for 3.4 Closed
Backwards Compatibility: Fully Compatible
Sprint: Query 15 (06/03/16), Query 16 (06/24/16)
Participants:

 Description   

Syntax

{
  $facet: {
    facetName1: [<stage1>, <stage2>, <stage3>],
    facetName2: [<stage4>, <stage5>, …],
    ...
  }
}

Examples

> db.example.insert([
    {
      _id: "product1",
      avgReview: 4.3,
      price: 21,
      category: "TVs",
      title: "Sony 42 inch HDTV",
      attributes: [
        {name: "type", value: "HD"},
        {name: "screen size", value: 42},
        {name: "manufacturer", value: "Sony"},
        ...
      ]
    }
    ...
])
> db.example.aggregate([
{$match: {category: "TVs"}},  // Match all relevant results.
{$facet: {
  "Screen Sizes": [
     {$unwind: "$attributes"},
     {$match: {"attributes.name": "screen size"}},
     {$group: {
         _id: { /* Use $switch to compute buckets for screen sizes */ },
         count: {$sum: 1}
     }}
   ],
 
   "Manufacturer": [
     {$match: {"attributes.name": "manufacturer"}},
     {$group: {_id: "$attributes.value", count: {$sum: 1}}},
     {$sort: {count: -1}}
     {$limit: 5}
   ]
}}
])
 
// Output.
{
  "Screen Size": [
    {_id: {min: MinKey, max: 32}, count: 32},
    {_id: {min: 32, max: 42}, count: 32},
    {_id: {min: 42, max: 50}, count: 33},
    {_id: {min: 50, max: MaxKey}, count: 33}
  ],
  "Manufacturer": [
    {_id: "Sony", count: 54},
    {_id: "Samsung", count: 45},
    {_id: "LG", count: 34},
    {_id: "Sharp", count: 22},
    {_id: "Vizio", count: 14},
  ]
}   

Behavior

  • names of sub-pipelines (keys in the document) must be unique.
  • This is a blocking stage.


 Comments   
Comment by Githook User [ 24/Jun/16 ]

Author:

{u'username': u'cswanson310', u'name': u'Charlie Swanson', u'email': u'charlie.swanson@mongodb.com'}

Message: SERVER-23654 Add $facet aggregation stage
Branch: master
https://github.com/mongodb/mongo/commit/46b4dfbdefe018e1f125a5ebac8b584b20274502

Generated at Thu Feb 08 04:04:04 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.