Home > Blockchain >  Updating Mongodb docs with an array of objects?
Updating Mongodb docs with an array of objects?

Time:12-28

Suppose we have this array:

const array = [{ code:1, pw:'abc'}, { code:2, pw:'grt'}, { code:3, pw:'tpo'}, { code:4, pw:'xyz'}]

and we have these docs in our db from model called User: [{ code:1, pw:'___'}, { code:2, pw:'___'}, { code:3, pw:'___'}, { code:4, pw:'___'}]

What's the most efficient way you'd suggest to update the pw fields from db with pws from the array at one shot (in Mongoose)? (we definitely want the codes from both arrays to match) Thank you.

CodePudding user response:

A simple and efficient option will be to use a bulk:

const usersBulk = userModel.collection.initializeUnorderedBulkOp();
for (const user of array) {
    usersBulk.find({code: user.code}).update({$set: {pw: user.pw}});
}
usersBulk.execute()

It can also be done in an update with pipeline query:

db.collection.updateMany(
  {code: {$in: codes}},
  [
    {$set: {pw: {
        $getField: {
          field: "pw",
          input: {
            $first: {
              $filter: {
                input: array,
                cond: {$eq: ["$$this.code", "$code"]}
              }
            }
          }
        }
    }}}
  ]
)

See how it works on the playground example

But I think it might be less efficient than a bulk update.

CodePudding user response:

You can do it like this:

db.collection.update({
  "code": {
    "$in": [
      1,
      2,
      3,
      4
    ]
  }
},
[
  {
    "$set": {
      "pw": {
        "$cond": {
          "if": {
            "$eq": [
              "$code",
              1
            ]
          },
          "then": "abc",
          "else": {
            "$cond": {
              "if": {
                "$eq": [
                  "$code",
                  2
                ]
              },
              "then": "grt",
              "else": {
                "$cond": {
                  "if": {
                    "$eq": [
                      "$code",
                      3
                    ]
                  },
                  "then": "tpo",
                  "else": "xyz"
                }
              }
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Working example

  • Related