Home > OS >  MongoDB v4.4 update value for a field based on existing value
MongoDB v4.4 update value for a field based on existing value

Time:10-24

I am using mongoose v5.13 on NodeJS

For a document whose id I know

{
    _id: ...,
    edible: 'fruit'
}

I want to update this document and do this

if (obj.edible == 'fruit') {
    obj.edible = 'apple';
} else if(obj.edible == 'vegetable') {
    obj.edible = 'carrot';
}

But this requires me to find first and then update, hence, two queries, my question is can I do it in one operation

CodePudding user response:

db.collection.update(
{
  _id: ObjectId("61723c7378b6d3a5a02d908e")
},
[
  {
    $set: {
      edible: {
         $switch: {
              branches: [
                  { case: { $eq: [ "$edible", 'fruit' ]  }, then: "apple" },
                  { case: { $eq: [ "$edible", 'vegetable' ]  }, then: "carrot" }
              ],
              default: "$edible"
         }
      }
    }
  }
])

Test Here

CodePudding user response:

Query

  • pipeline update requires >= MongoDB 4.2
  • you have 2 cases only you could use $cond also, but i used $switch so you can add more if needed

Test code here

db.collection.update({
  "_id": 1
},
[
  {
    "$set": {
      "edible": {
        "$switch": {
          "branches": [
            {
              "case": {
                "$eq": [
                  "$edible",
                  "fruit"
                ]
              },
              "then": "apple"
            },
            {
              "case": {
                "$eq": [
                  "$edible",
                  "vegetable"
                ]
              },
              "then": "carrot"
            }
          ],
          "default": "unknown"
        }
      }
    }
  }
])
  • Related