I have some data looking like this:
{'Type':'A',
'Attributes':[
{'Date':'2021-10-02', 'Value':5},
{'Date':'2021-09-30', 'Value':1},
{'Date':'2021-09-25', 'Value':13}
]
},
{'Type':'B',
'Attributes':[
{'Date':'2021-10-01', 'Value':36},
{'Date':'2021-09-15', 'Value':14},
{'Date':'2021-09-10', 'Value':18}
]
}
I would like to query for each document the document with the newest date. With the data above the desired result would be:
{'Type':'A', 'Date':'2021-10-02', 'Value':5}
{'Type':'B', 'Date':'2021-10-01', 'Value':36}
I managed to find some queries to find over all sub document only the global max. But I did not find the max for each document.
Thanks a lot for your help
CodePudding user response:
Storing date as string is generally considered as bad pratice. Suggest that you change your date field into date type. Fortunately for your case, you are using ISO date format so some effort could be saved.
You can do this in aggregation pipeline:
- use
$max
to find out the max date - use
$filter
to filter theAttributes
array to contains only the latest element $unwind
the array$project
to your expected output
Here is the Mongo playground for your reference.
CodePudding user response:
This keeps 1 member from Attributes only, the one with the max date. If you want to keep multiple ones use the @ray solution that keeps all members that have the max-date.
*mongoplayground can lose the order, of fields in a document, if you see wrong result, test it on your driver, its bug of mongoplayground tool
Query1 (local-way)
aggregate(
[{"$project":
{"maxDateValue":
{"$max":
{"$map":
{"input": "$Attributes",
"in": {"Date": "$$this.Date", "Value": "$$this.Value"}}}},
"Type": 1}},
{"$project":
{"Date": "$maxDateValue.Date", "Value": "$maxDateValue.Value"}}])
Query2 (unwind-way)
aggregate(
[{"$unwind": {"path": "$Attributes"}},
{"$group":
{"_id": "$Type",
"maxDate":
{"$max":
{"Date": "$Attributes.Date", "Value": "$Attributes.Value"}}}},
{"$project":
{"_id": 0,
"Type": "$_id",
"Date": "$maxDate.Date",
"Value": "$maxDate.Value"}}])