Search code examples
mongodbmongoosemongodb-querybson

How to find output in a collection using max and where condition in mongoDB


I am having a table called data here I have data called _id, timeStamp, value. I need to fetch max value using the where condition for a specific date

db.data.aggregate([ { "$group": { "_id": null, "MaximumValue": { "$max": "$value" }}}]);


Solution

  • You can use $match before you run $group:

    db.collection.aggregate([
        { $match: { timeStamp: 1584948532188.0 } },
        { $group: { _id: null, maxVal: { $max: "$value" } } }
    ])
    

    then $max is only applied on filtered set of documents

    Mongo Playground