Database

[{userId:"1",products:[{productId:"1",createdAt:"2023-07-02"},{productId:"2",createdAt:"2023-07-01"},{productId:"3",createdAt:"2023-07-03"},]}]

Query

db.collection.aggregate([{"$unwind":"$products"},{"$sort":{"products.createdAt":-1}},{"$group":{_id:"$_id",products:{"$push":"$products"}}}])

Result