MongoDB implements the query, the number of times that each user has a different status value.

there are two fields in the mongodb table: userId,status, where status has a value of 0 and 1, and a value of 2

.
{userId:1, status: 0}
{userId:1, status: 2}
{userId:1, status: 2}
{userId:2, status: 0}
{userId:2, status: 1}
{userId:2, status: 2}

I want to group queries according to users, and then filter out the number of occurrences of different status values for each user. How do I write the mongodb query statement?

for example, the final expected result above is:

[
    {userId:1, status_a: 1, status_b: 0, status_c: 2},
    {userId:2, status_a: 1, status_b: 1, status_c: 1}
]

similar to mysql

SELECT `userid`, COUNT( CASE WHEN `status` = "0" THEN 1 ELSE NULL END ), COUNT( CASE WHEN `status` = "1" THEN 1 ELSE NULL END ), COUNT( CASE WHEN `status` = "2" THEN 1 ELSE NULL END ) GROUP BY `userid`
Aug.06,2021

I think you mean SUM not COUNT :

  https://docs.mongodb.com/manu.


					
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b40e3e-34916.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b40e3e-34916.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?