mongodb - Changing from .group() to Aggregation -
i'm doing query in mongodb. want query iusing aggregation , not group. query using:
var query_part = { "shipdate" : { "$gte" : 19940101, "$lt" : 19950101 }, "partsupp.supplier.nation.name" : { $regex : '^canada'}, "partsupp.part.name" : { $regex : '^forest', $options : 'i' } }; var red = function(doc, out) { out.sum += doc.quantity; }; var half_total_quantity = db.lineitems.group( { key : "sum_quantity", cond : query_part, initial : { sum : 0 }, reduce : red })[0].sum / 2;
i'm trying change half_total_quantity calculation this:
db.lineitems.aggregate( { $match : {$and : [{"shipdate" : { "$gte" : 19940101, "$lt" : 19950101 }}, {"partsupp.supplier.nation.name" : { $regex : '^canada'}}, {"partsupp.part.name" : { $regex : '^forest', $options : 'i' }} ]}}, { $group : { sum_quantity : { $sum: "$quantity" } }} );
but not works, can me? thank you.
you never need $and
since all mongodb query operations "and" conditions unless explicitly stated otherwise.
also $group
requires , _id
, null
here indicate grouping "everything":
db.lineitems.aggregate([ { "$match": { "shipdate" : { "$gte" : 19940101, "$lt" : 19950101 }, "partsupp.supplier.nation.name" : { "$regex": '^canada' }, "partsupp.part.name" : { "$regex": '^forest', "$options": 'i' } }}, { "$group": { "_id": null, "sum_quantity": { "$sum": "$quantity" } }} ]);
not forget brackets []
since "list" of pipeline expressions, afterall.
and add "halftotalquantity" thing, $divide
in $project
stage, if must:
db.lineitems.aggregate([ { "$match": { "shipdate" : { "$gte" : 19940101, "$lt" : 19950101 }, "partsupp.supplier.nation.name" : { "$regex": '^canada' }, "partsupp.part.name" : { "$regex": '^forest', "$options": 'i' } }}, { "$group": { "_id": null, "sum_quantity": { "$sum": "$quantity" } }}, { "$project": { "half_quantity": { "$divide": [ "$sum_quantity", 2 ] } }} ]);
Comments
Post a Comment