Hello,
I have a collection which contains an array of objects, each containing a date and a price. I would like to be able to run an aggregate query that passes in an array of dates, check if any of those dates are contained within the object in the array, and if so, return the corresponding price. For example,
Sample data structure:
[
{
"key": 1
pricing: [
{
"date":"2022-09-09T16:00:00.000+00:00",
"price": 100
},
{
"date":"2022-09-10T16:00:00.000+00:00",
"price": 100
},
{
"date":"2022-09-11T16:00:00.000+00:00",
"price": 100
},
]
},
]
I’m not sure how to search an object in an array with an array, and if it exists project the value of another key. I’ve been trying something like this
const dates = [
'2022-09-07T16:00:00.000+00:00',
'2022-09-08T16:00:00.000+00:00',
'2022-09-09T16:00:00.000+00:00',
]
{
'$match': {
"pricing.date" : {$in : dates}
}
},
{
'$project': {
"pricing.date" : 1
"pricing.price" : 1
}
}
The data I would like back would be something like this
[
{date: 2022-09-09T16:00:00.000+00:00 ,price: 100}
]
I have also tried $elemMatch like this
{
"$match": {
"pricing.date": {
$elemMatch: {
$in: dates,
},
}
}
}
I have a non-working Playground here: https://mongoplayground.net/p/hyk-oYEF6RZ
Any help would be very much appreciated!
Cheers,
Matt