I have a big collection that holds lots of stats, since I want to generate reports, I am running a daily cron which aggregates data from the main collection to a smaller one
Personally, seems it looks like these are "delivery dates" for parts of an order I would do this:
{
'order_id': 'LaOPX',
'user_id': '777',
'parts': [
{ "date": ISODate("2015-04-18T00:00:00Z"), "qty": 100 },
{ "date": ISODate("2015-04-19T00:00:00Z"), "qty": 20 }
]
}
Where the dates where "actual date objects" in the database . If you wanted everything for all of user "777" data in all records then you can do:
db.collection.aggregate([
// Match the user between dates
{ "$match": {
"user_id": "777",
"parts.date": {
"$gte": new Date("2015-04-18"), "$lt": new Date("2015-04-20")
}
}},
// Unwind the array entries
{ "$unwind": "$parts" },
// Filter the required dates
{ "$match": {
"parts.date": {
"$gte": new Date("2015-04-18"), "$lt": new Date("2015-04-20")
}
}},
// Group per user
{ "$group": {
"_id": "$user_id",
"total": { "$sum": "$parts.qty" }
}}
])
It's much more flexible to use real dates in the data as range queries will always work as they should