MongoDB query group with 'sub' group -
from product stocks log have created mongodb collection. relevant fields are: sku, stock , date. every time products stock updated there new entry total stock.
the skus made of 2 parts. parent part, 'a' , variant or child part, '1', '2', '3', etc.. sku might this: 'a2'.
i can query single products stock, grouped day, query:
[{ $match: { sku: 'a2' } }, { $group: { _id: { year: {$year: '$date'}, day: {$dayofyear: '$date'} }, stock: { $min: '$stock' }, date: { $first: '$date' } } }, { $sort: { date: 1 } }]
note: want minimum stock each day.
but need query variations (minimum) stocks added up. can change $match object to:
[{ $match: { sku: /^a/ } }
how create 'sub' group in $group stage?
edit:
the data looks this:
{ sku: 'a1', date: '2015-01-01', stock: 15 } { sku: 'a1', date: '2015-01-01', stock: 14 } { sku: 'a2', date: '2015-01-01', stock: 20 }
two stocks 'a1' , 1 'a2' on single day. query (all skus grouped day) give me stock 14 result ($min of 3 values). want result 34. 20 (min a2) plus 14 (min a1)
if add sku _id field in group phase aggregate on well, i.e. group per sku, year & day.
db.stocks.aggregate( [ { $group: { _id: { sku: '$sku', year: {$year: '$date'}, day: {$dayofyear: '$date'} }, stock: { $min: '$stock' }, date: { $first: '$date' } } }, { $sort: { date: 1 } }] )
Comments
Post a Comment