Home > OS >  MongoDB: aggregation with update field by condition
MongoDB: aggregation with update field by condition

Time:12-03

Please tell me how can i update field with condition in aggregate?

[{_id:"1",val:"admin",...},{_id:"2",val:'employee',...},{_id:"3",val:"admin",...},...]

New data: "admin-en","employee-en"

Collection.aggregate([{
  $project: {
   $cond: {
 if: {$eq:"admin"},
then: {$set:"admin-en"},
if: {$eq:"employee"},
then: {$set: "employee-en"}
}
 }
}])

I'm most likely doing something wrong. Maybe there is some other way to update a field with a condition using aggregation

CodePudding user response:

You can't update in an aggregate query but you can use aggregate stages into a update query. Check Updates with Aggregation Pipeline.

By the way I'm not sure if I've understood correctly but maybe you only need this query:

db.collection.update({},
[
  {
    "$set": {
      "val": {
        "$concat": [
          "$val",
          "-en"
        ]
      }
    }
  }
],
{
  "multi": true
})

Example here.

But, if you want to use if/else statement you can try with $switch (which i.e. is an if/else structure):

db.collection.update({},
[
  {
    "$set": {
      "val": {
        "$switch": {
          "branches": [
            {
              "case": {
                "$eq": [
                  "$val",
                  "admin"
                ]
              },
              "then": "admin-en"
            },
            {
              "case": {
                "$eq": [
                  "$val",
                  "employee"
                ]
              },
              "then": "employee-en"
            }
          ],
          "default": "$val"
        }
      }
    }
  }
],
{
  "multi": true
})

Example here.

Also only using if/else example is here.

Note that:

  • First example will update all $val.
  • Second and third examples will update only $val with value "admin" or "employee".
  • Related