Is it possible to project based upon $cond?
{$project: {$cond: [ { $weekday: true }, then: current_day: 1, total_work_time_hours_base10_rounded: 1, total_worktime_seconds: 1,
weekday: 1,
weekend_day: 1, else: current_day: 1, total_work_time_hours_base10_rounded: 0, total_worktime_seconds: 0,
weekday: 0,
weekend_day: 0,] }
}
Displaying only certain fields in a $project stage?
Cheers,
Daniel
alexbevi
(Alex Bevilacqua)
2
@Daniel_Stege_Lindsjo,
Conditional projection can be done using the $$REMOVE variable.
For example:
db.foo.drop();
db.foo.insertMany([
{ current_day: 1 },
{ current_day: 2 },
{ current_day: 3 },
{ current_day: 4 },
{ current_day: 5 },
{ current_day: 6 },
{ current_day: 7 }
])
db.foo.aggregate([
{
$project: {
_id: 0,
current_day: 1,
weekday: { $and: [{ $gte: ["$current_day", 1] }, { $lte: ["$current_day", 5] } ] },
weekend_day: { $or: [{ $eq: ["$current_day", 6] }, { $eq: ["$current_day", 7] } ] }
}},
{ $project: {
weekday: { $cond: { if: "$weekday", then: "$weekday", else: "$$REMOVE" } },
weekend_day: { $cond: { if: "$weekend_day", then: "$weekend_day", else: "$$REMOVE" } }
}}
]);
// output
[
{
"weekday": true
},
{
"weekday": true
},
{
"weekday": true
},
{
"weekday": true
},
{
"weekday": true
},
{
"weekend_day": true
},
{
"weekend_day": true
}
]
3 Likes
system
(system)
Closed
3
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.