Search code examples
mongodbaggregate

Group MongoDB documents by field


I have a collection of say questions like below -

{
    question: "what's the question?",
    answer: "some answer",
    points: 10
},
{
    question: "what's the question again?",
    answer: "some answer again",
    points: 40
},
...

The questions which are answered will have an answer in it's document and vice-versa. I want to group all the answered and not-answered questions using aggregate, to get an output like -

{
  answered: [{...}, {...}],
  unanswered: [{...}, {...}]
}

How would the aggregate query for this look like?


Solution

  • There are multiple way to do this.

    One is using $facet as follows :

    db.collection.aggregate([
      {
        "$facet": {
          "answered": [
            {
              $match: {
                answer: {
                  $exists: true
                },
                
              },
              
            },
            
          ],
          "unanswered": [
            {
              $match: {
                answer: {
                  $exists: false
                },
                
              },
              
            },
            
          ],
          
        }
      }
    ])