1

Am trying to find a way to get the minimum number of orders between 2019-03-17 and 2019-03-19 excluding 2019-03-15 from the results ..

{ 
"_id" : ObjectId("5c8ffdadde62bf097d54ec47"), 
"productId" : "32886845998", 
"orders" : [
    {
        "date" : ISODate("2019-03-15T00:00:00.000+0000"), 
        "orders" : NumberInt(9)
    }, 
    {
        "date" : ISODate("2019-03-17T00:00:00.000+0000"), 
        "orders" : NumberInt(21)
    }, 
    {
        "date" : ISODate("2019-03-18T00:00:00.000+0000"), 
        "orders" : NumberInt(20)
    }, 
    {
        "date" : ISODate("2019-03-19T00:00:00.000+0000"), 
        "orders" : NumberInt(30)
    }
]

}

I tried using $min and $max operator but that didn't help because it iterated through the full array to find maximum & minimum

db.products.aggregate([
{
    $project: {
        maximum: {
            $reduce: {
                input: "$orders",
                initialValue: 0,
                in: {
                    $max: [
                        "$$value",
                        {
                            $cond: [
                                { $gte: [ "$$this.date", ISODate("2019-03-17T00:00:00.000+0000") ] },
                                "$$this.orders",
                                0
                            ]
                        }
                    ]
                }
            }
        }
    }
}

])

1 Answer 1

2

You can use $filter to apply filtering by orders.date and then you can apply $min and $max on filtered set:

db.col.aggregate([
    {
        $project: {
            filteredOrders: {
                $filter: {
                    input: "$orders",
                    cond: {
                        $and: [
                            { $gte: [ "$$this.date", ISODate("2019-03-17T00:00:00.000+0000") ] },
                            { $lte: [ "$$this.date", ISODate("2019-03-19T00:00:00.000+0000") ] },
                        ]
                    }
                }
            }
        }
    },
    {
        $project: {
            min: { $min: "$filteredOrders.orders" },
            max: { $max: "$filteredOrders.orders" },
        }
    }
])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mickl ,you are awesome as MongoDB

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.