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

Issue

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

Solution

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"}}}}])

Answered By – Takis _

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.