0

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
}

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

$rename seems to be an update operator. But I need to rename field due projection.
1

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 }

2 Comments

Thanks, this looks like what I need. What about persons without purchases, will it be output? Is there a way to filter out amount without miss person?
The persons without purchases will not be considered as $unwind won't return anything if the purchases array is empty or doesnt exist.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.