【问题标题】:The dollar ($) prefixed field '$divide' in "weight.$divide" is not valid for storage"weight.$divide" 中的美元 ($) 前缀字段 '$divide' 对存储无效
【发布时间】:2023-03-27 02:35:01
【问题描述】:

我在 NodeJS 中有以下更新查询,其中包含 mongoose 3.5.5 使用的底层 mongodb 驱动程序,使用最新的 MongoDB 服务器 4.2.5 社区:

    await mongoose.connection.db.collection('cluster1kms').updateOne({"location.coordinates": [point.longitude, point.latitude]}, {
                        $set: {
                            weight: {
                                $divide: [
                                    {
                                        $add: [
                                            {
                                                $multiply: ["$weight", "$count"]
                                            },
                                            point.weight
                                        ]
                                    },
                                    {
                                        $add: ["$count", 1]
                                    }
                                ]
                            }
                        },
                        $inc: {"count": 1}
                    }, {upsert: false});

如标题所示,我不断收到$divide 不是有效存储名称的问题。 MongoDB 应该允许在更新中聚合管道,但我似乎没有成功。在网上的MongoDB web shell中也尝试了同样的方法,错误是一样的。

我错过了什么吗?

谢谢

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    正如你所说,MongoDB 从 4.2 版开始允许 aggregated pipelines,但使用它们的语法发生了一些变化。

    在您的情况下,这有点简单,我们只需要使用[] 包装更新部分并更改$inc,因为流水线更新不支持它。

    await mongoose.connection.db.collection('cluster1kms').updateOne({"location.coordinates": [point.longitude, point.latitude]},
        [
            {
                $set: {
                    weight: {
                        $divide: [
                            {
                                $add: [
                                    {
                                        $multiply: ["$weight", "$count"]
                                    },
                                    point.weight
                                ]
                            },
                            {
                                $add: ["$count", 1]
                            }
                        ]
                    },
                    count: {$add: ["$count", 1]} // this replaces the $inc.
                }
            }
        ])
    

    【讨论】:

    • 妈的,整天都在做这件事,还以为我一直在看一个字一个字,除了括号。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2019-12-27
    • 2017-12-13
    • 2020-05-24
    • 1970-01-01
    相关资源
    最近更新 更多