Abhay Raj Singh
Abhay Raj Singh

Reputation: 99

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

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

Upvotes: 0

Views: 77

Answers (2)

Takis
Takis

Reputation: 8695

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

PlayMongo

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

Upvotes: 1

Pramisha C P
Pramisha C P

Reputation: 327

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

Upvotes: 2

Related Questions