【问题标题】:How to get the unread count如何获得未读计数
【发布时间】:2019-10-18 18:56:23
【问题描述】:

我创建了如下消息架构:-

{ 
_id : message_unique_id,
recipients : [ user_id1,user_id2,user_id3 ],
message : "Hello Word",
readBy : [user_id2,user_id3],
chatId : unique_id_for_every_chat
}

现在我能够获取每个对话的最后一条消息,但无法获取未读消息的计数。我使用的是如下:-

Messages.aggregate([
{ $match : {recipients : {$in : [my_user_id]},
{ $project : {
chatId : 1,
recipients : 1,
readBy : 1
}, { $group : {
_id : "$chatId",
message : "$last" : "$message"} }}]).exec();

上述查询运行良好,并返回用户每次聊天的最后一条消息。但现在我也想获得未读消息计数。我使用了以下查询:-

Messages.aggregate([
    { $match : {recipients : {$in : [my_user_id]},
    { $project : {
    chatId : 1,
    recipients : 1,
    readBy : 1,
    unread: {  
            $cond: { if : { "$readBy" : {$in : [my_user_id]}}, then : 
            0, else : 1 }
        }
    }, 
    { $group : {
          _id : "$chatId",
           unreadCount : { $sum: "$unread" },   
           message : "$last" : "$message"} }}]).exec();

但是这个查询返回 null。请帮忙。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    将 $project 读取值替换为以下内容:

     unread: {$cond: {
                if: {$gte: [{$indexOfArray: ["$readBy", my_user_id]}, 0]}, then: 0, else: 1
             }}
    

    试试

     unread: {
            $cond: {
              if: {
                "$setIsSubset": [
                  [my_user_id],
                  "$readBy"
                ]
              },
              then: 0,
              else: 1
            }
          }
    

    这在我的情况下有效。

    【讨论】:

    • 它给出错误。 MongoError : 无效的运算符“$indexOfArray”。
    • 我想我需要升级版本才能使用它。目前版本是 3.2.22
    • 我添加了固定 $in 的新代码,你能试试吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    相关资源
    最近更新 更多