Imagine that you have this document:

{

"time" : ISODate("2013-03-03T14:43:51.468Z"),

"quantity" : 5,

"totalPaid" : 5423

}

First we want to project to a document that has an additional field we need: day of the week.

{

"$project" : {

"quantity" : 1,

"totalPaid" : 1,

"_id" : 0,

"dow" : {

"$dayOfWeek" : "$time"

}

}

}

{

"$group" : {

"_id" : "$dow",

"total" : {

"$sum" : "$totalPaid"

},

"count" : {

"$sum" : "$quantity"

}

}

}

{ "$sort" : { "_id" : 1 } }

I broke it up into steps so that you can see how I came up with an incredibly long and complex expression - it's the kind of thing that I could never get all the parenthesis to match up correctly if I didn't do it programmatically, or in sequence of simple steps. I'm also saving the last step into a variable that I will use in my final pipeline.

var ifFri = { $cond: [ {$eq:[6,"$_id"]}, "Friday","Saturday"]}

var ifThu = { $cond: [ {$eq:[5,"$_id"]}, "Thursday",ifFri]}

var ifWed = { $cond: [ {$eq:[4,"$_id"]}, "Wednesday",ifThu]}

var ifTue = { $cond: [ {$eq:[3,"$_id"]}, "Tuesday",ifWed]}

var ifMon = { $cond: [ {$eq:[2,"$_id"]}, "Monday",ifTue]}

var dayOfWeek = { $cond: [ {$eq:[1,"$_id"]}, "Sunday",ifMon]}

{

"$project" : {

"_id" : 0,

"dow" : dayOfWeek,

"avgPrice" : {

"$divide" : [

{

"$divide" : [

"$totalPaid",

"$quantity"

]

},

100

]

}

}

}

Meanwhile, let's look at what 'dayOfWeek' expression actually looks like:

{

"$cond" : [

{

"$eq" : [

1,

"$_id"

]

},

"Sunday",

{

"$cond" : [

{

"$eq" : [

2,

"$_id"

]

},

"Monday",

{

"$cond" : [

{

"$eq" : [

3,

"$_id"

]

},

"Tuesday",

{

"$cond" : [

{

"$eq" : [

4,

"$_id"

]

},

"Wednesday",

{

"$cond" : [

{

"$eq" : [

5,

"$_id"

]

},

"Thursday",

{

"$cond" : [

{

"$eq" : [

6,

"$_id"

]

},

"Friday",

"Saturday"

]

}

]

}

]

}

]

}

]

}

]

}

{

"result" : [

{

"dow" : "Sunday",

"avgPrice" : 18.15

},

{

"dow" : "Monday",

"avgPrice" : 18.06

},

{

"dow" : "Tuesday",

"avgPrice" : 33.50

},

{

"dow" : "Wednesday",

"avgPrice" : 50.66

},

{

"dow" : "Thursday",

"avgPrice" : 55.89

},

{

"dow" : "Friday",

"avgPrice" : 54.00

},

{

"dow" : "Saturday",

"avgPrice" : 52.53

}

],

"ok" : 1

}