gpt4 book ai didi

node.js - Mongoose :find() 忽略重复值

转载 作者:行者123 更新时间:2023-12-05 02:54:04 25 4
gpt4 key购买 nike

我有一个“聊天” Mongoose Schema它具有以下属性:

const schema = mongoose.Schema({
...
recipient: {
type: mongoose.Types.ObjectId,
required: true,
ref: 'User',
},
sender: {
type: mongoose.Types.ObjectId,
required: true,
ref: 'User',
},
content: {
type: String,
},
...
}, {
timestamps: true,
});

一般来说,我想获取用户每次对话的最后一条消息。这意味着我需要提供一个用户 ID(可以存储在 senderrecipient 字段中)并取回用户与其他每个用户的最后一条消息(由 createdAt 表示)。

示例:假设我有以下 document小号:

[
{
recipient: "One",
sender: "Two",
createdAt: ISODate("2014-01-01T08:00:00Z"),

},
{
recipient: "One",
sender: "Three",
createdAt: ISODate("2014-02-15T08:00:00Z")
},
{
recipient: "Two",
sender: "One",
createdAt: ISODate("2014-02-16T12:05:10Z")
}
]

将“One”作为输入 - 来自 Model.find(...) 的期望结果是:

[
{
recipient: "One",
sender: "Three",
createdAt: ISODate("2014-02-15T08:00:00Z")
},
{
recipient: "Two",
sender: "One",
createdAt: ISODate("2014-02-16T12:05:10Z")
}
]

最佳答案

使用示例数据:

[
{
recipient: "One",
sender: "Two",
createdAt: ISODate("2014-01-01T08:00:00Z"),
content: "Hi Mr. One! - Two"
},
{
recipient: "One",
sender: "Three",
createdAt: ISODate("2014-02-15T08:00:00Z"),
content: "Hello One! - Three"
},
{
recipient: "Two",
sender: "One",
createdAt: ISODate("2014-02-16T12:05:10Z"),
content: "Whats up, Two? - One"
}
]

查看以下聚合:https://mongoplayground.net/p/DTSDWX3aLWe

它...

  • 使用 $match 按收件人或发件人过滤所有邮件。返回匹配当前用户的那些 (One)
  • 使用包含收件人$addFields添加一个conversationWith字段,如果它是给用户One的消息或 sender 如果它是一条消息由用户 One 发送
  • 使用 $sort 按日期对邮件进行排序
  • 通过新的 conversationWith 字段使用 $group 对所有消息进行分组,并将最新的消息返回为 firstMessage

完整的聚合管道:

db.collection.aggregate([
{
$match: {
$and: [
{
$or: [
{
recipient: "One"
},
{
sender: "One"
}
],

},

]
}
},
{
$addFields: {
conversationWith: {
$cond: {
if: {
$eq: [
"$sender",
"One"
]
},
then: "$recipient",
else: "$sender"
}
}
}
},
{
$sort: {
createdAt: -1
}
},
{
$group: {
_id: "$conversationWith",
firstMessage: {
$first: "$$ROOT"
}
}
}
])

使用 mongoplayground,您可以一个一个地删除聚合步骤,以查看每个步骤的作用。

尝试:

  • 只有$match步骤
  • $匹配 + $addFields
  • $match + $addFields + $sort
  • [..]

为了最好的理解。

关于node.js - Mongoose :find() 忽略重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61969645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com