0

RELATED TO THIS: MongoDB update with condition https://stackoverflow.com/a/62816731/15931755 This is my first time using this site to post so bare with my structure.

QUESTION: I need to update a mongodb collection field ex: collectionName.gender based on the current values of some other field (or the same field) ex: collection.gender

This was a PUT route for me Original post was missing a few pieces, this is the full code block for anyone who needs the full PUT route.

ANSWER:

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
node dev
  • 1
  • 1

1 Answers1

0

This is the way. Same as above.

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'})
}
node dev
  • 1
  • 1