aggregation framework - How to get count of multidimentional array with conditions in mongodb? -
i have mongo document chatmessages as
{ "_id" : objectid("5784dcd9db2c60b54b8b45d3"), "sender_id" : "55505ad6b5a0925f4c8b7707", "receivers_id" : [ "57715368db2c60e5208b4579" ], "messages" : [ { "_id" : objectid("5784e0fadb2c605c6d8b4578"), "sender" : "57715368db2c60e5208b4579", "message" : "hai", "send_at" : numberlong(1468326138), "read_by" : [ { "user" : "55505ad6b5a0925f4c8b7707", "at" : numberlong(0) } ] } ], "updated_at" : numberlong(1468327157), "created_at" : numberlong(1468327157) }
i need find total unread messages document above. suppose current user_id 55505ad6b5a0925f4c8b7707
. have been stuck somewhere results. me guys
update
$unread_messages = chatmessages::find([ 'conditions' => [ '$or' => [ ['sender_id' => $user_id], ['receivers_id' => ['$elemmatch' => ['$eq' => $user_id]]] ], 'messages.sender' => ['$ne' => $user_id] ] ]);
first query should have shown results receiving null value
as manual $or operator, don't need conditions
before it. example in mongo shell:
db.chats.find( {$or:[ {'sender_id': "55505ad6b5a0925f4c8b7707"}, {'receivers_id':{ $elemmatch:{ $eq:"55505ad6b5a0925f4c8b7707" } } } ], 'messages.sender':{ $ne:"55505ad6b5a0925f4c8b7707" } } )
you utilise aggregation pipeline using combination of $match, $unwind , $sum. example, match , unwind :
db.chats.aggregate([ {$match: {$or:[ {'sender_id': 1}, {'receivers_id':{ $elemmatch:{$eq:1}}}], 'messages.sender':{$ne:1}}}, {$unwind:"$messages"}, {$unwind:"$messages.read_by"} ])
once have result, group , sum accordingly. (unfortunately, example doesn't show how unread detected, , there's 1 message)
having said that, need re-consider data models. having messages stored in embedded documents, may reach bson document size limit of 16mb once have many messages. current model may suitable small chats, won't scale well. see data model examples , patterns more information.
Comments
Post a Comment