首页 > 解决方案 > 如何使用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

标签: mongodbmongoosepagination

解决方案


聚合$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')]
                    }
                }
            }
        }
    }

])

推荐阅读