mongodb - 如何使用nodeJS在MongoDb中对子数组进行分页
问题描述
我正在使用 MongoDB 构建聊天应用程序(用于对象建模的猫鼬)
我有房间集合,并将消息存储在房间文档的数组中。
演示:
{
"_id" : ObjectId("5e91bcd6cd1630213d95f810"),
"users" : [
ObjectId("5e57d64d92cc878760086980"),
ObjectId("5e79f882def34451678278c7")
],
"messages" : [
{
"_id" : ObjectId("5e95bdeb43756876056c46fc"),
"text" : "World",
"user" : ObjectId("5e79f882def34451678278c7"),
"createdAt" : ISODate("2020-04-14T13:43:07.953Z")
},
{
"_id" : ObjectId("5e95bc5c43756876056c46fb"),
"text" : "Hello",
"user" : ObjectId("5e79f882def34451678278c7"),
"createdAt" : ISODate("2020-04-14T13:36:28.284Z")
}
]
}
现在我想检索 10 到 10 条消息,但我不能使用$slice方法。
我怎样才能检索这样的消息:
SELECT * FROM messages WHERE createdAt > "2020-04-14T13:36:28.284Z" LIMIT 0, 10
解决方案
聚合$filter帮助了我。感谢@MoazzamArif。
Chat.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId(roomId)
}
},
{
$project: {
messages: {
$filter: {
input: "$messages",
as: "message",
cond: {
$gt: ['$$message.createdAt', new Date('2020-04-14T13:36:28.284Z')]
}
}
}
}
}
])
推荐阅读
- c - 用 scanf 分配指针的整数
- azure - How to Terraform assignment of Azure User Managed Identity to a storage account?
- typhoon - 使用 Typhoon 在运行时注入闭包时的 EXC_BAD_ACCESS
- windows - 我们可以比较两个有日期的文件并找到较新的日期吗
- css - 自定义字体在移动设备上不起作用
- r - 我正在尝试通过句子和单词注释来提取 pos 标签,其中一些句子给出了句子注释错误
- sql - 将数据库与主模板数据库进行比较
- ios - Dropbox 错误 - 'uploadData:mode:autorename:clientModified:mute:propertyGroups:inputData:'
- ios - 在 Swift 中将音频转换为二进制数据
- sql - 找不到驱动程序 (SQL: select * from `users` where `email` = admin@example.com limit 1)