mongodb - Find all Mongo documents for which the max value in an array matches a query -
given document structure such this:
{ values: [ { value: 10 }, { value: 20 }, { value: 30 } ] } i search documents maximum value in array matches query.
eg. if search documents maximum less 25 example above not match since 30 > 25.
how can this?
using .aggregate() method provides access aggregation pipeline.
if on version 3.2 or newer stage in pipeline $redact use $$keep , $$prune variables return or discard documents don't match criteria. in $cond expression use $max operator return maximum value in "values" array return the $map operator because $redact stage mentioned in documentation:
db.collection.aggregate([ { "$redact": { "$cond": [ { "$lt": [ { "$max": { "$map": { "input": "$values", "as": "value", "in": "$$value.value" } }}, 25 ]}, "$$keep", "$$prune" ] }} ]) from version 3.0 backward need first denormalize "values" array using $unwind operator $group documents _id; compute maximum using $max , use $push accumulator operator return array of values. last stage $redact stage.
db.collection.aggregate([ { "$unwind": "$values" }, { "$group": { "_id": "$_id", "maxvalues": { "$max": "$values.value"}, "values": { "$push": "$values" } }}, { "$redact": { "$cond": [ { "$lt": [ "$maxvalues", 25 ] }, "$$keep", "$$prune" ] }} ])
Comments
Post a Comment