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.


					
Menu