Home > OS >  How to combine find and update to 1 update
How to combine find and update to 1 update

Time:12-23

I'm using Spring Data MongoTemplate, trying to optimize mongodb update. Can I make only 1 update without a find() to check status of the document in db first:

  • If status is not "Blocked", update the status and add to the actions.
  • If status is "Blocked", just add to the actions, not update to the status.
Java object to update:
status: "Display",
action: "Show"

mongodb:
{
    status: "Blocked",
    actions: [
        "Show",
        "Hide",
        "Show",
        ...
    ]
}

CodePudding user response:

You can do an update with aggregation pipeline. Do the conditional checking on the status field in the $addFields stage.

db.collection.update({},
[
  {
    "$addFields": {
      "userInput": {
        status: "Display",
        action: "Show"
      }
    }
  },
  {
    "$addFields": {
      "status": {
        "$cond": {
          "if": {
            $ne: [
              "$status",
              "Blocked"
            ]
          },
          "then": "$userInput.status",
          "else": "Blocked"
        }
      },
      actions: {
        "$concatArrays": [
          [
            "$userInput.action"
          ],
          "$actions"
        ]
      }
    }
  },
  {
    "$unset": "userInput"
  }
],
{
  multi: true
})

Here is the Mongo playground for your reference.

  • Related