【问题标题】:MongoDB update with condition - update based on other existing field valueMongoDB 使用条件更新 - 基于其他现有字段值的更新
【发布时间】:2021-05-15 22:37:21
【问题描述】:

与此相关:MongoDB 更新条件 https://stackoverflow.com/a/62816731/15931755 这是我第一次使用这个网站来发布我的结构。

问题:我需要根据其他字段(或同一字段)的当前值来更新 mongodb 集合字段,例如:collectionName.gender,例如:collection.gender

这对我来说是一条 PUT 路线 原始帖子缺少一些部分,这是任何需要完整 PUT 路线的人的完整代码块。

回答:

exports.someName = function (req, res) {

    db.customer.updateMany(
    
        {},
        [
            {
                $set: {
                    gender: {
                   //if you need need to $set a nested field I replaced gender with 'parentfield.gender'
                        $switch: {
                            branches: [
                                {case: {$eq: ['$gender', 'male']}, then: 'female'},
                                {case: {$eq: ['$gender', 'female']}, then: 'male'}
                                //you can add more conditions, I used 4 conditions
                            ],
                            default: ''
                        }
                    }
                }
            }
        ], function (err, doc) {
            console.log(doc)
        })
    res.status(200).json({success: 1, message: 'successfully updated based on conditions'})
}

// good luck and remember to keep answering

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    就是这样。同上。

    exports.someName = function (req, res) {
    
        db.customer.updateMany(
        
            {},
            [
                {
                    $set: {
                        gender: {
                       //if you need need to $set a nested field I replaced gender with 'parentfield.gender'
                            $switch: {
                                branches: [
                                    {case: {$eq: ['$gender', 'male']}, then: 'female'},
                                    {case: {$eq: ['$gender', 'female']}, then: 'male'}
                                    //you can add more conditions, I used 4 conditions
                                ],
                                default: ''
                            }
                        }
                    }
                }
            ], function (err, doc) {
                console.log(doc)
            })
        res.status(200).json({success: 1, message: 'successfully updated based on conditions'})
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-02
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2019-08-20
      • 2016-02-20
      相关资源
      最近更新 更多