Search code examples
mongodbaggregation-frameworkfacet

How to iterate through a set to get field value in MongoDB


Can somebody tell me please if is possible to iterate through a set to create a field value for key in mongodb result. If I have $facet state in pipeline like:

'missing': [{'$group': {'_id': '$foo', 'woo': {'$addToSet': '$wwo'}}},
           {'$project': {'missing_woo': {'$setDifference': [woo_set, '$woo']}}

I would like to get result where code value will be the key like

{'missing_woo': 'missing_woo1'}, {'missing_woo': 'missing_woo2'},... {'missing_woo': 'missing_wooN'}

so that I can iterate through the set generated at $project and to create field values


Solution

  • You can simply use $unwind:

    db.collection.aggregate([
      {
        $facet: {
          missing: [
            {$group: {_id: "$foo", woo: {$addToSet: "$wwo"}}},
            {$project: {_id: 0, missing_woo: 
              {$setDifference: [
                    [
                      "woo1",
                      "woo2",
                      "wooN",
                      "missing_woo1",
                      "missing_woo2",
                      "missing_wooN"
                    ],
                    "$woo"
                  ]
                }
              }
            },
            {$unwind: "$missing_woo"}
          ]
        }
      }
    ])
    

    See how it works on the playground example