【问题标题】:updateMany gives Error: collection.updateOne requires update operatorupdateMany 给出错误:collection.updateOne 需要更新运算符
【发布时间】:2020-08-18 13:12:13
【问题描述】:

我正在尝试使用 updateMany 和聚合管道更新许多记录,但是当我尝试运行它时,我不断收到此错误。我对这个错误感到困惑,因为它提到了 updateOne 而这不是我正在使用的。我想更新一些记录,设置玩过的游戏数,然后根据 score 字段的当前值设置低分和高分。

我已经阅读了 updateMany 的文档,据我所知,我拥有应有的方式。

[Error] Error: collection.updateOne requires update operator

db.items.updateMany(
    {'game': 'pacman'},
    [
        {$set: {'games_played': 53}},
        {$set: {
            $min: {'score_low': '$score'},
            $max: {'score_high': '$score'}
        }}  
    ]
)

我也尝试了以下并得到同样的错误。

db.items.updateMany(
    {'game': 'pacman'},
    [
        {$set: {'games_played': 53}},
        {$set: {
            'score_low': {$min: {'score_low': '$score'}},
            'score_high': {$max: {'score_high': '$score'}}
        }}  
    ]
)

编辑:

这给出了同样的错误。

db.items.updateMany(
    {'game': 'pacman'},
    [
        {$set: {'games_played': 53}},
        {$set: {
            'score_low': {$min: '$score'},
            'score_high': {$max: '$score'}
        }}  
    ]
)

【问题讨论】:

  • 这是正确的语法:'score_low': { $min: '$score' }

标签: mongodb


【解决方案1】:

看起来像是与$min$max 相关的语法问题。您可以尝试使用updatemulti:true 选项或updateMany,如下所示:

 db.items.updateMany(
        {'game': 'pacman'},
        [
            {$set: {'games_played': 53}},
            {$set: {
                'score_low': {$min: '$score'}},
                'score_high': {$max: '$score'}}
            }}  
        ])

db.items.update(
    {'game': 'pacman'},
    [
        {$set: {'games_played': 53}},
        {$set: {
            'score_low': {$min: '$score'}},
            'score_high': {$max: '$score'}}
        }}  
    ], {multi:true}
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2013-06-24
    • 1970-01-01
    • 2017-04-17
    • 2015-01-02
    相关资源
    最近更新 更多