I am struggling to write this query.
From the following dataset, I want to find out the documents who's resources array have 'EC2' and print out ONLY that element from the array.
Data:
[
{
"projectName": "first"
"resources": [
{
"resource": "EC2",
"region": "ap-south-1",
"params": {
"ImageId": "ami-0bcf5425cdc1d8a85",
"InstanceType": "t2.micro",
}
},
{
"resource": "S3",
"region": "ap-south-1",
"params": {
"Bucket": "test-bucket"
}
}
],
}
]
Expected output:
{
"resource": "EC2",
"region": "ap-south-1",
"params": {
"ImageId": "ami-0bcf5425cdc1d8a85",
"InstanceType": "t2.micro",
}
}
The query that I have tried :
const projects = await Project.aggregate([
{
$match: {
resources: {
$elemMatch: {
resource: { $eq: 'EC2' },
},
},
},
},
{
$project: {
resourceName: '$resources.resource',
region: '$resources.region' // and so on
},
},
]);
^^ This is returning other elements from the resources array as well