【问题标题】:MongoDB - $merge that works in Compass but not from a Node.js LambdaMongoDB - $merge 在 Compass 中有效,但不适用于 Node.js Lambda
【发布时间】:2020-10-01 23:13:01
【问题描述】:

我有一个在 Compass 中运行良好的聚合管道,但是当我从 NodeJS Lambda 中使用它时,它什么也没做。没有错误,当然也没有连接问题或类似问题,因为我还在使用相同的连接详细信息动态插入数据和创建索引。为什么这不起作用?

Lambda 代码:

// 'db' obtained from connection pooling elsewhere

await db.collection(collectionName).aggregate(aggregationStatement);

汇总声明:

[
    {
        "$match": {
            "type": "costForecast"
        }
    },
    {
        "$sort": {
            "when": 1
        }
    },
    {
        "$group": {
            "_id": {
                "type": "$type"
            },
            "when": {
                "$last": "$when"
            },
            "type": {
                "$last": "$type"
            },
            "serviceId": {
                "$last": "$serviceId"
            },
            "serviceName": {
                "$last": "$serviceName"
            },
            "data": {
                "$last": "$data"
            }
        }
    },
    {
        "$project": {
            "when": 1,
            "type": 1,
            "serviceId": 1,
            "serviceName": 1,
            "data": "$data.ForecastResultsByTime"
        }
    },
    {
        "$merge": {
            "into": "CostsOut",
            "on": [ "type", "serviceId" ],
            "whenMatched": "replace",
            "whenNotMatched": "insert"
        }
    }
]

不用说所有字段都存在,$merge 的目标集合包含支持“on”声明的唯一索引。我试图实现的功能是在原始集合中找到“costForecast”项的最新示例,挑选几个字段并将数据稍微展平,然后插入或更新带有文档的“CostsOut”集合“ type”和“serviceId”作为唯一的复合索引。

非常感谢您的帮助。

【问题讨论】:

  • 你好!您找到问题的答案了吗? :)

标签: node.js mongodb lambda aggregation


【解决方案1】:

.aggregate() 是不可等待的,它只是返回一个游标而不是一个承诺。

要告诉 Mongo,它应该执行聚合,你必须调用 .toArray() 或 .forEach()

await db.collection(collectionName).aggregate(aggregationStatement).toArray();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2018-05-21
    • 1970-01-01
    • 2014-12-21
    • 2015-06-23
    相关资源
    最近更新 更多