Home > Mobile >  How can i update array value in mongodb?
How can i update array value in mongodb?

Time:03-31

For Examples,

{
    "_id":ObjectId("6245131fdbcda3639d75c951"),
    "username": "joy"
    "data" : [ 
        {
            "_id" : ObjectId("6245131fdbcda3639d75c953"),
            "value_1" : "hello1"
            "value_2" : "thank you1"
        }, 
        {
            "_id" : ObjectId("6245131fdbcda3639d75c954"),
            "value_1" : "hello2"
            "value_2" : "thank you2"
        }, 

    ]
}

I want to edit one of data object and delete old one and push edited one

because i want to the edited object will be last index of array.

i want to get this result.

{
    "_id":ObjectId("6245131fdbcda3639d75c951"),
    "username": "joy"
    "data" : [ 
        {
            "_id" : ObjectId("6245131fdbcda3639d75c954"),
            "value_1" : "hello2"
            "value_2" : "thank you2"
        }, 
        {
            "_id" : ObjectId("6245131fdbcda3639d75c953"),
            "value_1" : "change data from hello1"
            "value_2" : "change data from thank you1"
        }, 

    ]
}

I tried it but i got error.

db.getCollection('profile').update(
{username:"joy"},
{
  {
    "$pull": {"data": 
                    {"_id": ObjectId("6245131fdbcda3639d75c953")}
    },
  },
  {
    "$push": {"data": 
       {
       "_id" : ObjectId("6245131fdbcda3639d75c953"),
       "value_1" : "change data from hello1"
       "value_2" : "change data from thank you1"
       }
     },
  }
})

How can i get the value? thank you. :)

CodePudding user response:

MongoDB will not allow multiple operations/operators in a single field, you can use update with aggregation pipeline starting from 4.2,

  • $filter to iterate loop of data array and filter the documents that are not equal to your input _id,
  • $concatArrays to concat filtered data array and new object that you want to add in the last index of data array
db.getCollection('profile').update(
  { username: "joy" },
  [{
    $set: {
      data: {
        $concatArrays: [
          {
            $filter: {
              input: "$data",
              cond: {
                $ne: ["$$this._id", "6245131fdbcda3639d75c953"]
              }
            }
          },
          [
            {
              _id: "6245131fdbcda3639d75c953",
              value_1: "change data from hello1",
              value_2: "change data from thank you1"
            }
          ]
        ]
      }
    }
  }]
)

Playground

  • Related