Given a document with a subdocument from a $lookup
aggregation, I want to project a specific field form the subdocument based on the field of the $$ROOT
document. Example:
{
"date": "2023-08-20",
"code": "USD",
"exchange_rates": {
"USD": 1.01,
"EUR": 2.01,
"CNY": 3.01
}
}
I want to get:
{
"date": "2023-08-20",
"exchange_rate": 1.01
}
This subdocument came from a $lookup
operation, so maybe I can put the project (or any other command) directly inside the pipeline
argument from this aggregation directly.
2
Answers
One option is:
See how it works on the playground example
Given I have the following collections:
one
, which contains:two
, which contains:{date: '2023-08-20'}
I can use the following pipeline to get the desired result from collection one, based on the date. I used $addFields to override the exchange_rates to USD.
Will result in: