I have records in a collection of the following format:
"_id" : "2013-05-23",
"authors_who_sold_books" : [
{
"id" : "Charles Dickens",
"num_sold" : 1,
"customers" : [
{
"time_bought" : 1368627290,
"customer_id" : 9715923
}
]
},
{
"id" : "JRR Tolkien",
"num_sold" : 2,
"customers" : [
{
"date_bought" : 1368540890,
"customer_id" : 9872345
},
{
"date_bought" : 1368537290,
"customer_id" : 9163893
}
]
}
]
}
There is a record for each date, many of which will contain the same author. I'm after a query that returns the following:
{
"_id" : "Charles Dickens",
"num_sold" : 235,
"customers" : [
{
"date_bought" : 1368627290,
"customer_id" : 9715923
},
{
"date_bought" : 1368622358,
"customer_id" : 9876234
},
etc...
]
}
I've tried various combinations of aggregate, group, unwind and project but still can't quite get there and would really appreciate any suggestions.
For extra points, I'm actually doing this using the Ruby gem, so code specific to this would be great. I can convert normal MongoDB query language, however.