Hi Team,
Want to know is there facility in $cond can use the $regex to match if condition rather using $eq operation.
For Example collection is as below,
**[**
** {name: 'A', city: 'Mumbai',status:'Yes'},**
** {name: 'B', city: 'Tokyo',status:'No'},**
** {name: 'C', city: 'New York',status:'Yes'},**
** {name: 'D', city: 'Mumbai',status:'Yes'},**
** {name: 'E', city: 'Mumbai',status:'No'},**
** {name: 'F', city: 'Mumbai',status:'yes'},**
**]**
Need to find out the city wise status count for Yes and No
Expected output:
[
{city: 'Mumbai', statusYes: 3, statusNo: 1},
{city: 'Tokyo', statusYes: 0, statusNo: 1},
{city: 'New York', statusYes: 1, statusNo: 0}
]
Tried using aggregation of $group operation by,
$group: { _id: {city: "$city"}, city: { $last: "$city"}, statusYes: { $sum: { $cond: { if: {$eq:["$status","Yes"]}, then: 1, else: 0 } } }, statusNo: { $sum: { $cond: { if: {$eq:["$status","No"]}, then: 1, else: 0 } } }, }
And then it results,
[ {city: 'Mumbai', statusYes: 2, statusNo: 1}, {city: 'Tokyo', statusYes: 0, statusNo: 1}, {city: 'New York', statusYes: 1, statusNo: 0} ]
Since count getting wrong the I’ve tried using $regex but it not able to find correct result.
Used:
if: { $eq: ["$status", /yes/i] }
shows 0 count.
And if I used $regex like,
if: { status: {$regex: 'yes', $options: 'i'}}
then shows an expression must have exactly one field.
Can anyone please suggest what is missing here.
Regards,
Jitendra.