Mongodb: update many array elements by index with different data

Viewed 29

I get a mongo document like below

// document example
{ 
"_id" : ObjectId("62c447e3cf7aee7b78d39908"), 
"gid" : "1234", 
"branch_trans" : [ 
  { "branch_id" : "branchId123", "op" : "test_op" },
  { "branch_id" : "branchId456", "op" : "test_op" },
  { "branch_id" : "branchId789", "op" : "test_op"}] 
}

Golang struct:

type GlobalTrans struct {
    ID         primitive.ObjectID `bson:"_id"`
    Gid        string             `bson:"gid,omitempty"`
    BranchTrans []BranchTrans `bson:"brach_trans,omitempty"`
}

type BranchTrans struct {
    BranchID     string     `bson:"branch_id,omitempty"`
    Op           string     `bson:"op,omitempty"`
}

I have a startPositon variable, and an array variable []branches, now I want to update branch_trans from the index startPositon using []branches. For example, if startPositon = 1 and []branches is

[
  { "branch_id" : "branchId456", "op" : "op1" },
  { "branch_id" : "branchId789", "op" : "op2"}
]

After updating, the document will look like:

{ 
"_id" : ObjectId("62c447e3cf7aee7b78d39908"), 
"gid" : "1234", 
"branch_trans" : [ 
  { "branch_id" : "branchId123", "op" : "test_op" },
  { "branch_id" : "branchId456", "op" : "op1" },
  { "branch_id" : "branchId789", "op" : "op2"}] 
}

I don't know how to do that, can anybody help me?

1 Answers

You can $slice the not changed array and concat with the $concatArray to get the expected branch_trans. Then can you update the existing branch_trans key inside document using $replaceWith and $setField with aggregate pipeline.

db.branch.aggregate([
  {
    "$replaceWith": {
      "$setField": {
        input: "$$ROOT",
        "field": "branch_trans",
        "value": {
          "$concatArrays": [
            {
              $slice: [
                "$branch_trans",
                0,
                1
              ]
            },
            [
              {
                "branch_id": "branchId456",
                "op": "op1"
              },
              {
                "branch_id": "branchId789",
                "op": "op2"
              }
            ]
          ]
        }
      }
    }
  }
])

Playground

Related