Consider this collection of test results:
[{
_id: ObjectId(...),
name: "Test1",
acts: [
{
name: "act1",
tests: [
{name: "test1", result: true},
{name: "test2", result: true}]
}]
},
{
_id: ObjectId(...),
name: "Test2",
acts: [
{
name: "act1",
tests: [
{name: "test1", result: true},
{name: "test2", result: false}]
},
{
name: "act2",
tests: [
{name: "test3", result: true}]
}]
}]
I'm trying to use aggregations to create a calculated field with the sum of all test results, I want something like this:
[{
_id: ObjectId(...),
name: "Test1",
result: true, //new aggregated value
acts: [
{
name: "act1",
result: true, //new aggregated value
tests: [
{name: "test1", result: true},
{name: "test2", result: true}]
}]
},
{
_id: ObjectId(...),
name: "Test2",
result: false, //new aggregated value
acts: [
{
name: "act1",
result: false, //new aggregated value
tests: [
{name: "test1", result: true},
{name: "test2", result: false}]
},
{
name: "act2",
result: true, //new aggregated value
tests: [
{name: "test3", result: true}]
}]
}]
I have tried using aggregate and $unwind, $project and $group:
aggregate([
{$unwind: "$acts"},
{$unwind: "$acts.tests"},
{$project: {name: 1, acts: 1, failed: {$cond: {if: {$eq: ["$acts.tests.test", "true" ]}, then: 0, else: 1}}}},
{$group: {_id: "$_id", failedCount: {$sum: "$failed"}, acts: {$push: "$acts.tests"}}}
])
But I can't get it to reverse the $unwind operation, I only get the resulting data structure to differ from the original. Is it possible to get the result to look exactly like the original collection but with the new aggregated values?
/gemigspam