1
votes

I'm struggling when I $unwind more than one field from a Sub-Document.

Here's what the data looks like:-

{
   resp: {
      field1: 'yes',
      field2: ''
},
{
   resp: {
      field1: 'yes',
      field2: ''
}

etc,etc...

If I process an Aggregation Pipeline for ONE field, it works OK, so this works...

{ $unwind: "$resp" },
{ $unwind: "$resp.field1" },
{ $project: { field1: "$resp.field1" } }
{ $group: {
     _id: 1,
     field1: { $sum: { $cond: [{ $eq: ["$field1","yes"] },1,0] } } 
   }
}

But if I now want to return field 2 in the same aggregation, using the following, it will return a count of Zero for both fields, whereas previously field1 had a count > Zero.

{ $unwind: "$resp" },
{ $unwind: "$resp.field1" },
{ $unwind: "$resp.field2" },
{ 
 $project: { 
     field1: "$resp.field1",
     field2: "$resp.field2" 
}, 
{ $group: {
     _id: 1,
     field1: { $sum: { $cond: [{ $eq: ["$field1","yes"] },1,0] } },
     field2: { $sum: { $cond: [{ $eq: ["$field2","yes"] },1,0] } }
   }
}

Any suggestions would be much appreciated.

1

1 Answers

0
votes

it seems the above is the correct way to do this, but I'd happily take alternative suggestions. The error was in may mapping of the fields in the $project stage. When typing the issue into SO I realised where the problem was !