STO
STO

Reputation: 10658

Mongo DB query: project array element to property

Having following data

{
   "_id": "...",
   "name": "John",
   "purchases": [
       {
            "date": {
                "$date": "2016-12-20T00:00:00.000Z"
            },
            "amount": 1000
       },
       {
            "date": {
                "$date": "2016-12-23T00:00:00.000Z"
            },
            "amount": 100
       }    

   ]
}

How to get latest purchase amount as result field with different name?

To get next result:

{
    "_id": "...",
    "name": "John",
    "purchases": [
           {
                "date": {
                    "$date": "2016-12-20T00:00:00.000Z"
                },
                "amount": 1000
           },
           {
                "date": {
                    "$date": "2016-12-23T00:00:00.000Z"
                },
                "amount": 100
           }    

       ]
    },
    "latestPurchaseAmount": 100
}

Upvotes: 0

Views: 351

Answers (2)

s7vr
s7vr

Reputation: 75984

You can do something like this. This below query will unwind all the purchases in the collection and, sort the purchases by date descending and, limit the result to one and project the corresponding amount.

db.purchases.aggregate([{
    $unwind: "$purchases"
}, {
    $sort: {
        "purchases.date": -1
    }
}, {
    $limit: 1
}, {
    $project: {
        _id: 0,
        latestPurchaseAmount: "$purchases.amount"
    }
}]);

Output

{ "latestPurchaseAmount" : 100 }

Upvotes: 1

G. Mansour
G. Mansour

Reputation: 696

You have to use the $rename take a look at this link

And for your last item you should look at this it will helps you Link

Upvotes: 1

Related Questions