【问题标题】:Add the number of results in the result of the MongoDB query and put the results in an Array在MongoDB查询的结果中添加结果数,并将结果放入一个Array中
【发布时间】:2023-01-14 18:26:54
【问题描述】:

我想在查询响应中添加结果数,并将结果放在一个数组中。 你能帮我么?

这是我当前的 MongoDB 查询:https://sourceb.in/kUL9kKDq2c
以下是预期结果的示例(包含 500 个结果的示例):

{
    response: [{
            _id: new ObjectId("627d7828990fff996621d5ea"),
            Name: 'test date',
            ActorId: 3,
            MovieId: 1,
            State: 100,
            ActorWatched: [110],
            RatedCount: 2,
            PublishedDate: 2022 - 05 - 12 T21: 21: 41.081 Z,
            AverageRating: 5,
            StarCoinsEarned: 100
        },
        {
            _id: new ObjectId("627d7828990fff996621d5ea"),
            Name: 'test date',
            ActorId: 3,
            MovieId: 2,
            State: 100,
            ActorWatched: [],
            RatedCount: 1,
            PublishedDate: 2022 - 05 - 12 T21: 21: 41.081 Z,
            AverageRating: 5,
            StarCoinsEarned: 100
        }],
    count: 500
}

预先感谢您的帮助!

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    这是我所做的...我编写了两个单独的聚合管道,一个带有跳过和限制,一个没有跳过和限制,并执行了两个查询。

    const responsePipeline = [stage1, stage2, skipStage, limitStage];
    const countPipeline = [stage1, stage2, countStage];
    const responseData = await yourModel.aggregate(responsePipeline);
    const countData = await yourModel.aggregate(countPipeline);
    

    希望这可以帮助。

    【讨论】:

    • 嘿,谢谢你的回答,这就是我现在正在做的,但它对我不起作用,因为对同一件事的 2 个请求执行时间太长。我如何在同一个查询中执行此操作以提高性能?
    猜你喜欢
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    相关资源
    最近更新 更多