Search code examples
mongodbaggregation-frameworkaggregate-functionsfacet

Mongodb aggregate $facet


I'm trying to use a $facet stage of a aggregate pipeline to match and group documents, but I suspect my syntax is out.

Could anybody tell me what's wrong with this please? Keep getting the message "A Pipeline stage specification object must contain exact one field".

[
  {
   '$match': {
   'Id': 59
  }
  }, {
   '$unwind': {
   'path': '$Vehicles'
 }
 }, {

    // It's this stage that's playing up.
    '$facet': {
       'Offers': [
         {
            '$match': { 'Vehicles.VehicleGrouping': 'OOTW' }, 
            '$group': {
                '_id': '$Vehicles.Manufacturer', 
                'count': { '$sum': 1 }
            }
         }
       ]
     }
     // End of problematic stage.

   }
 ]

Thanks.


Solution

  • You have put $match and $group, in one object, try this:

    db.collection.aggregate([
      {
        "$match": {
          "Id": 59
        }
      },
      {
        "$unwind": {
          "path": "$Vehicles"
        }
      },
      {
        // It's this stage that's playing up.
        "$facet": {
          "Offers": [
            {
              "$match": {
                "Vehicles.VehicleGrouping": "OOTW"
              }
            },
            {
              "$group": {
                "_id": "$Vehicles.Manufacturer",
                "count": {
                  "$sum": 1
                }
              }
            }
          ]
        }  
      }
    ])