Mongodb aggregation quesry for message unread count group by group_id -




here problem : in mongodb database, have collection messages :

{   'id': 1,   'message': 'message 1',   'groups': [1],   'readby': ['cust1','cust2'],   'status': '1' } {   'id': 2,   'message': 'message 2',   'groups': [1],   'readby': ['cust2'],   'status': '1' } {   'id': 3,   'message': 'message 3',   'groups': [2],   'readby': ['cust2','cust1'],   'status': '1' } {   'id': 4,   'message': 'message 4',   'groups': [2],   'readby': ['cust2'],   'status': '1' } {   'id': 5,   'message': 'message 5',   'groups': [2],   'readby': ['cust2'],   'status': '1' } 

i have collection customer, in have maintained groups ids. 'cust1' part of group id = [1,2]. want total group count messages not read cust1. in above case count should 2.

i have tried using below query, returns total unread message count.

db.messages.aggregate(    {$unwind : "$groups" },    {$match:{       "groups": {             "$in": ["1","2"]         },          "status": "1",         "readby": {             "$ne": "cust1"         }    }},    {$group:{_id:null,count:{$sum:1}}} ).pretty() 

below query satisfy above functionality.

db.messages.aggregate(    {$unwind : "$groups" },    {$match:{       "groups": {             "$in": ["1","2"]         },          "status": "1",         "readby": {             "$ne": "cust1"         }    }},    {$group:{_id:"$groups"}},    {$group:{_id:null,count:{$sum:1}}} ) 




wiki

Comments

Popular posts from this blog

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -