I am trying to retrieve all the documents where one of the value of the attribute in the nested object starts with "-". Below is the sample document - I want to search the "counts" array object and find if any of the "value" attribute in the nested object starts with "-"
{
"_id": "XYZ",
"departureDate": "2020-10-09",
"travelerCounts": [
{
"counts": [
{
"key": "J",
"value": "4"
},
{
"key": "Y",
"value": "4"
}
],
"travelCountType": "ActualCapacity"
},
...
]
},
{
"_id": "XYZ1",
"departureDate": "2020-10-09",
"travelerCounts": [
{
"counts": [
{
"key": "J",
"value": "18"
},
{
"key": "Y",
"value": "-1"
}
],
"travelCountType": "ActualCapacity"
}
...
]
}
I have tried this but no luck -
db.myCollection.find(
{departureDate: "2020-10-09"},
{
"travelerCounts": {
"$elemMatch": {
"travelCountType": "ActualCapacity",
"counts": {
"$elemMatch": {
"value": { $regex : /^-/ }
}
}
}
}
})
Please help
As state in the official MongoDB documentation:
This works for retrieving all documents that at least one of its nested documents contains a value which starts with a dash:
In your example, you are using the projection parameter (second parameter in find method) for the filter, which is incorrect.
EDIT: The solution for retrieving all collection documents that at least have one document in the nested travelerCounts, that meets the following conditions:
Query: