1

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. :)

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.