在mongodb中查找所有未读对话

在mongodb中查找所有未读对话,mongodb,mongoose,mongodb-query,Mongodb,Mongoose,Mongodb Query,我正在使用mongoose制作一个群组聊天对话模式,但在过去的几天里,我在查询时遇到了麻烦。我的目标是查找用户的所有未读对话 我的模式如下所示: const ConversationSchema = new Schema( { participants: [{ user: mongoose.Schema.Types.ObjectId, lastViewed: Date, // the last date the user checked the convers

我正在使用mongoose制作一个群组聊天对话模式,但在过去的几天里,我在查询时遇到了麻烦。我的目标是查找用户的所有未读对话

我的模式如下所示:

const ConversationSchema = new Schema(
  {
    participants: [{
      user: mongoose.Schema.Types.ObjectId,
      lastViewed: Date, // the last date the user checked the conversation
    }],
    updatedAt: Date,
  }
);
这是简化的样本数据:

   {
     participants: [
       {
         user: 'A',
         lastViewed: 'Jan 11'
       },
       {
         user: 'B',
         lastViewed: 'Jan 13'
       },
     ],
     updatedAt: 'Jan 13',
   }
对我来说,如果出现以下情况,用户的对话将被视为未读:

  • 用户在参与者数组中
  • 对话
    updatedAt
    值大于参与者的
    lastview
最后,我的mongoose find函数如下所示

const conversations = await conversationModel.find({
  'participants.user': user.id,
  $expr: {
    $gt: ['updatedAt', 'participants.user.lastViewed'],
  },
});

因此,当我试图查询用户B的未读对话时,我应该期望一个空的
[]
结果为
Jan 13=Jan 13
,但我仍然在结果中得到对话。我认为问题出在
$expr
参数中,但我不确定添加什么,因为它处理数组。非常感谢您的帮助。

在引用字段时,您需要在
$expr
中使用美元符号,但这并不能解决您的问题。问题是,您试图查找特定用户,因此可能存在这样一种情况:用户
a
存在,但其他用户的
lastViewed
低于
updatedAt
(单独条件)

最好先使用并找到您的用户,然后在该特定子文档上应用您的条件:

db.collection.find({
    $expr: {
        $let: {
            vars: { user: { $arrayElemAt: [ { $filter: { input: "$participants", cond: { $eq: [ "$$this.user", "A" ] } } }, 0 ] }},
            in: {
                $and: [
                    { $ne: [ "$$user", null ] },
                    { $gt: [ "$updatedAt", "$$user.lastViewed" ] }
                ]
            }
        }
    }
})


我还建议您将日期从字符串转换为ISODate格式,以避免出现任何问题,如2013年1月<代码>与9日<代码>比较。

这正是我所需要的,感谢您的链接和建议。我会调查的