Reputation: 283
I m trying to build a useful report for a page I m creating, but I m having issues with formatting the data, take a look at this below :
db.getCollection('store_spendings').aggregate(
{
"$project": { "spend_dollars": 1, "comments.text": 1, "comments.user.user_id": 1, "store_id": 1 }
},
{
"$lookup":
{
"from": "corporate_spendings",
"localField": "store_id",
"foreignField": "store_id",
"as": "corporate_spendings"
}
},
{
"$match": { "corporate_spendings.region_id": 10816 }
},
{
"$project": { "spend_dollars": "$spend_dollars", "comments": 1, "prior_year_spend_dollars": "$corporate_spendings.prior_year_spend_dollars" } }
)
I get a result like this :
[
spend_dollars: 321312,
comments: [...comments data],
prior_year_spend_dollars: [1231231],
...
]
I get correct results except the format of data is a bit off for prior_year_spend_dollars
. I would like it to be a field just like spend_dollars
rather than an array.
I've tried using $first
but apparently it only works with group. Right now I do this 'first' operation in my app, but ideally it would be done on the db.
My ideal output with be like this :
[
spend_dollars: 321312,
comments: [...comments data],
prior_year_spend_dollars: 1231231,
...
]
How can I do that?
Upvotes: 0
Views: 79
Reputation: 75984
Try arrayElemAt
operator in project
stage which lets you pick value from array based on index.
"prior_year_spend_dollars":
{"$arrayElemAt": ["$corporate_spendings.
prior_year_spend_dollars", 0]}
Upvotes: 1