I have implemented the solution provided in this post How to filter array in subdocument with MongoDB
The method works correctly, except for cases where none of the elements in the array pass the test. In such situations, I end up with an empty array without any parent data.
SAMPLE DATA
{
"_id": "53712c7238b8d900008ef71c",
"dealerName": "TestDealer",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="611504121521150412154f020e0c">[email protected]</a>",
"address": {..},
"inventories": [
{
"title": "active",
"vehicles": [
{
"_id": "53712fa138b8d900008ef720",
"createdAt": "2014-05-12T20:08:00.000Z",
"tags": [
"vehicle"
],
"opts": {...},
"listed": false,
"disclosures": {...},
"details": {...}
},
{
"_id": "53712fa138b8d900008ef720",
"createdAt": "2014-05-12T20:08:00.000Z",
"tags": [...],
"opts": {...},
"listed": true,
"disclosures": {...},
"details": {...}
}
]
},
{
"title": "sold",
"vehicles": []
}
]
}
GOAL
My aim is to retrieve the top-level information (dealerName, email) of a user (document) and a property named vehicles containing all vehicles in the "active" inventory that have the property listed set to true
.
CURRENT PROGRESS
This is the query I am using. (I utilize Mongoose but primarily rely on native Mongo features)
{
$match:
email: params.username
}
{
$unwind: '$inventories'
}
{
$match:
'inventories.title': 'active'
}
{
$unwind:
'$inventories.vehicles'
}
{
$match:
'inventories.vehicles.listed':
$eq: true
}
{
$group:
_id: '$_id'
dealerName:
$first: '$dealerName'
email:
$first: '$email'
address:
$first: '$address'
vehicles:
$push: '$inventories.vehicles'
}
ISSUE
Initially, I believed my query was correct, but when none of the vehicles are flagged as listed
, the query returns an empty array. This outcome is expected due to
{
$match:
'inventories.vehicles.listed':
$eq: true
}
not finding any matches, yet I still wish to obtain the dealerName and email
EXPECTED OUTPUT WHEN NO VEHICLES MATCH
[{"dealerName": "TestDealer", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cebaabbdba8ebaabbdbae0ada1a3">[email protected]</a>", vehicles : []}]
ACTUAL RESULT
[]