0

How can i replace all elements from a mongodb array element. As in below example, my requirement is to remove both object from skills array and add new elements in it.

{
    "_id": "uniqueid",
    "skills": [
        { "skill": "dancer" },
        { "skill": "singer" }
    ]
}

I need to replace all element of skills array field. How this can be achieved using mongodb java driver, or other query types?

1
  • You can overwrite your array. Just use db.colname.find({"_id": "uniqueid"}, {$set:{"skills":new array}}) Commented Oct 25, 2018 at 12:49

1 Answer 1

2

You just need to use $set operator $set to set skills to a new value which will be an array of the new element you want to replace with.

 db.collectionName.update(
   { _id: 'uniqueid' },
   { $set:
      {            
        skills: [{'new elements'}]
      }
   }
)

if you want to remove all elements set the skills to an empty array {skills: []}

if you want to remove a certain elements based on a value use $pull operator $pull

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.