2017-06-03 43 views
0

我正在計算用戶是對話成員的所有會話中的未讀消息。如果用戶的ID在讀取器陣列中,則用戶讀取消息。Sum子數組的長度

以下返回存在未讀消息的會話數。但如何計算所有未讀郵件?

db.getCollection('conversations').count({ 
    'messages.readers': { $size: 1 }, //i.e. only the message author is in the message.readers array. 
    'members': { $in: [ObjectId("59320e38188c5050ac99be8f")] } 
}) 

我檢查了聚合方法,但我不確定它是否是正確的方法。以下內容返回所有消息的數量。

 db.getCollection('conversations').aggregate([ 
    {$match : { 
     'members': { $in: [ObjectId("59320e38188c5050ac99be8f")] } 
    }}, 
    {$group: {_id: null, count: {$sum: {$size: "$messages"}}}}, 
]) 

enter image description here

+0

您可以使用查詢來檢查用戶是否在'members'數組中,用戶不在'messages.readers'數組中,然後是count。例如'db.getCollection('conversations')。count({'members':ObjectId(「59320e38188c5050ac99be8f」),「messages.readers」:{$ ne:ObjectId(「59320e38188c5050ac99be8f」)}})' – Veeram

+0

當然,但是這將計算會話的數量而不是未讀消息的數量。 – nFu9DT

+0

我想我以錯誤的方式設計了這個數據庫。 – nFu9DT

回答

1

你可以試試下面的聚集管道。

下面的查詢將$unwind在每個匹配的談話所有信息和應用$cond表達$sum運營商的內部檢查,如果用戶不在messages.readers,返回1,如果在$group階段比賽或者0。

db.getCollection('conversations').aggregate([ 
    {$match : {'members': ObjectId("59320e38188c5050ac99be8f") }}, 
    {$unwind : "$messages"}, 
    {$group: {_id: null, count: {$sum: {$cond: [{ $ne: ["messages.readers", ObjectId("59320e38188c5050ac99be8f")] }, 1, 0]}}}} 
]) 

因此,$unwind是昂貴的操作,不應該優先於其他的選擇,但我不認爲你的情況很可能和$unwind以下$match是更好一點。