Reputation: 19664
I am trying to aggregate a field based on a date range. I can't figure out how to create a $cond expression that will evaluate more than one expression. I am trying to use the logical $or operator but with no luck.
db.project.aggregate(
{ $match : { brand : 4 } },
{ $project : {
_id : 0,
brand : 1,
count : 1,
day : 1}
},
{ $group : {
_id : "$brand",
TotalCount : { $sum : "$count" },
TimeRangeCount : {$sum: { $cond: [ { $gte: [ "$day", new Date(2014, 0, 6) ], {$or: [$lte: [ "$day", new Date(2014, 0, 8) ]]} }, "$count", 0 ] }}
}}
)
Is it possible to nest $or within $cond?
Thanks!
Upvotes: 5
Views: 11148
Reputation: 29
To answer your original question, yes you can use $or within a $cond.
However, in your case this would be semantically incorrect as you are looking for a range between dates.
For future reference you could use something like this, if for example you wanted to map multiple values to a single value. This is basically saying "if you encounter val1 or val2 or val3 in someField change them to val4.
db.someCollection.aggregate([
{
someField: {
$cond: [
{$or: [
{$eq: ['$someField', 'val1']},
{$eq: ['$someField', 'val2']},
{$eq: ['$someField', 'val3']}
]
},
'val4',
'$someField'
]}
}]
Upvotes: 2
Reputation: 19664
I believe I got it using $and
db.project.aggregate(
{ $match : { brand : 4 } },
{
$project : {
_id : 0,
brand : 1,
count : 1,
day : 1
}
},
{
$group : {
_id : "$brand",
TotalCount : { $sum : "$count" },
TimeRangeCount : {
$sum: {
$cond: [
{$and: [
{$gte: ["dDay", new Date(2014, 0, 6)]},
{$lte: ["$day", new Date(2014, 0, 8)]}
]},
"$count",
0
]
}
}
}
}
)
Upvotes: 9