skip to Main Content

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?

2

Answers


  1. 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
                },
                
              },
              
            },
            
          ],
          
        }
      }
    ])
    
    Login or Signup to reply.
  2. One option is to use $group instead of $facet, as $facet does not use indices:

    db.collection.aggregate([
      {$group: {
          _id: 0,
          answered: {$push: {$cond: [
                {$eq: [{$toBool: "$answer"}, true]},
                "$$ROOT",
                "$$REMOVE"
          ]}},
          unanswered: {$push: {$cond: [
                {$ne: [{$toBool: "$answer"}, true]},
                "$$ROOT",
                "$$REMOVE"
          ]}},
      }},
      {$unset: "_id"}
    ])
    

    See how it works on the playground example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search