0

I need to edit an item at a position(index) in an array without having to add an index to each item.

// The record in the collection
const data = {
    library: 'The book store',
    books: ['bookA', 'bookB', 'bookC']

}

I'm looking to only change the item at index 1 within the books array

I'm trying the following but it's not working...

return Record.updateOne(
    {
      video_id,
    },
    {
      $set: {
        "books[1]": 'Book H'
      },
    },
    (err, data) => {
      if (err) {
        console.log(err);
      }
      return data;
    }
  );

Any ideas?

2 Answers 2

2

as long as you need to always update the second element in the array, so you can use the dot notation

your query should be something like that

return Record.updateOne(
  { video_id }, // filter part
  {
    $set: { // update part
      "books.1": 'Book H'
    },
  },
  (err, data) => { // call back function
    if (err) {
      console.log(err);
    }
    return data;
  }
);

hope it helps

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

4 Comments

Thank you @Mohammed Yousry what happen if I have another nested array instead of a string?
you can use the same logic, if you want to update the array element at index = 1, but this element is an array, and you want to update this inner array element at index = 2 for example, then the update part will be like this 'books.1.2': 'Book H'
If you mean an array of objects, not array of strings, something like that books: [{ name: 'Book A', author: 'Author 1' }, { name: 'Book B, author: 'Author 2' }, { name: 'Book C', author: 'Author 3' }], and you want to update the array element at index = 1, say you want to update the book name, then the query will be 'books.1.name': 'Book H', hope it's clear now
Perfect! thank you @Mohammed Yousry it worked! do you know if is possible to pass the key dynamically or programmatically? for instance I'm trying to pass create the key by interpolating const key = content.${highlights[0].node}.children.${highlights[0].children} and then trying to use it as [key]:value. but is not recognizing the key
0

I am demonstrating in pure MongoDB query without unnecessary details so everyone can understand easily.

db.getCollection("libraries").update({/* your filter*/}, {
    $set: {
        "books.1": "Book H"
    }
})

2 Comments

Thank you @denizkanmaz, but what if I have another nested object inside the array?
That was not the case in your question :) . And apparently, you've already got the answer in another comment.

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.