Home > Net >  Group MongoDB documents by field
Group MongoDB documents by field

Time:01-13

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?

CodePudding user response:

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

CodePudding user response:

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
            },
            
          },
          
        },
        
      ],
      
    }
  }
])
  • Related