【问题标题】:$nin condition inside $sum for a nested value嵌套值的 $sum 内的 $nin 条件
【发布时间】:2020-10-12 17:23:35
【问题描述】:

我正在使用nodejs 和mongodb 制作聊天应用程序。目前我有多个用户、房间和消息的集合。每条消息都包含对房间、发件人的引用以及对已阅读该消息的用户的引用数组。

我正在尝试使用 mongodb 的聚合来获取当前用户的未读消息计数。这是我当前的代码:

Room.aggregate([
    {
        $match: { participants: request.currentUser._id },
    },
    {
        $lookup: {
            from: 'messages',
            localField: '_id',
            foreignField: 'room',
            as: 'messages',
        },
    },
    {
        $unwind: {
            path: '$messages',
            preserveNullAndEmptyArrays: true,
        },
    },
    {
        $sort: { 'messages.createdAt': -1 },
    },
    {
        $group: {
            _id: '$_id',
            name: { $first: '$name' },
            type: { $first: '$type' },
            participants: { $first: '$participants' },
            latestMessage: { $first: '$messages' },
            createdAt: { $first: '$createdAt' },
            updatedAt: { $first: '$updatedAt' },
            unreads: {
                $sum: {
                    $cond: {
                        if: {
                            $nin: [request.currentUser._id, '$messages.read']
                        }
                    }
                }
            },
        },
    },
])

此代码总是抛出Unrecognized expression '$nin' 错误。如何在$sum 中使用这样的条件来获得适当的结果?

@Ashh 请求的消息文档示例:

{
    "_id" : ObjectId("5ef0796fdb424a92c4200cdd"),
    "read" : [ 
        ObjectId("5ef078df7ce82f2e5cf3b586")
    ],
    "content" : "Test message",
    "sender" : ObjectId("5ef078df7ce82f2e5cf3b586"),
    "room" : ObjectId("5ed4ffcdd13f45b4104a1669"),
    "createdAt" : ISODate("2020-06-22T09:27:11.017Z"),
    "updatedAt" : ISODate("2020-06-22T09:27:11.017Z")
}

还有一个样板间文件:

{
    "_id" : ObjectId("5ed4ffcdd13f45b4104a1669"),
    "participants" : [ 
        ObjectId("5ed4ffbcd13f45b4104a1667"), 
        ObjectId("5ef078df7ce82f2e5cf3b586")
    ],
    "pending" : [],
    "name" : "Global",
    "type" : "CHANNEL",
    "creator" : ObjectId("5ed4ffbcd13f45b4104a1667"),
    "createdAt" : ISODate("2020-06-01T13:17:01.935Z"),
    "updatedAt" : ISODate("2020-06-01T13:17:01.935Z")
}

【问题讨论】:

  • 你试过[Op.nin]

标签: javascript node.js mongodb mongoose nosql


【解决方案1】:

$nin 是查询运算符,您必须在 $group 中使用聚合运算符。所以改为使用$not 和$in

{ $not:{ $in: [request.currentUser._id, { $ifNull: ['$messages.read', []] }] } }
                    

【讨论】:

【解决方案2】:

$nin 不是聚合运算符,但 $in 是,您可以使用 $in 反转逻辑

$cond 有两种语法

{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }

和

{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }

我们需要用 0 替换真案例,用 1 替换假案例,因为我们将计算数组中 不 的案例

        $sum: {
          $cond: [
            { $in: [request.currentUser._id, "$messages.read"] },
            0, // add 0 if in array
            1 // add 1 if not in array
          ]
        }

如果messages.read不存在,会报错,最好用$ifNull包裹

        $sum: {
          $cond: [
            { $in: [request.currentUser._id, { $ifNull:[ "$messages.read", []] }] },
            0, // add 0 if in array
            1 // add 1 if not in array
          ]
        }

【讨论】:

  • 正如我已经对@Ashh 的帖子发表评论的那样,messages.read 始终存在,但它仍然会抛出它丢失的错误,很好奇可能导致此类问题的原因
  • 嗯,是的,这实际上可能是问题所在,因为一个房间没有任何消息。甚至没有考虑过这种情况
  • 其实$ifNull 应该已经说明了这一点,你确定你试过$ifNull 吗?
  • 是的,除了当房间里没有消息时它返回 1 作为总和
  • 您提到每条消息总是至少有一次阅读,对吧?我猜是发件人?也许我们可以从那开始工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 2021-11-01
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多