Home > Back-end >  How to update an array within a object in mongodb
How to update an array within a object in mongodb

Time:06-04

im trying to update an array inside an object but i didnt find the right way to do this. my document looks like this:

{ "_id" : ObjectId("62792b4a0c9c5a00b6a8e17b"), "username" : "user_1", "words" : [ { "word" : "RATIONAL", "subwords" : [ "RAT", "TAN" ] }, { "word" : "YOUNGER", "subwords" : [ "YOU", "YOUR" ] } ] }

i want to push to subwords array with a specific word for example i want to push "AT" to the subwords of "RATIONAL" thanks for the help :)

CodePudding user response:

You can use filter() javascript function to get "RATIONNAL" and then push the desired value into the subwords array.

Example supposed that there is only ONE word RATIONNAL and that it exists. If it not the case, you need to improve this code to deal with all cases.

let myObject = JSON.parse('{ "_id" : "62792b4a0c9c5a00b6a8e17b", "username" : "user_1", "words" : [ { "word" : "RATIONAL", "subwords" : [ "RAT", "TAN" ] }, { "word" : "YOUNGER", "subwords" : [ "YOU", "YOUR" ] } ] }');
console.log('Before: %o', myObject);

myObject.words.filter(word => word.word == 'RATIONAL')[0].subwords.push('AT');
console.log('After: %o', myObject);

Running this will print this to console:

Before: {
  _id: '62792b4a0c9c5a00b6a8e17b',
  username: 'user_1',
  words: [
    { word: 'RATIONAL', subwords: [ 'RAT', 'TAN', [length]: 2 ] },
    { word: 'YOUNGER', subwords: [ 'YOU', 'YOUR', [length]: 2 ] },
    [length]: 2
  ]
}

After: {
  _id: '62792b4a0c9c5a00b6a8e17b',
  username: 'user_1',
  words: [
    { word: 'RATIONAL', subwords: [ 'RAT', 'TAN', 'AT', [length]: 3 ] },
    { word: 'YOUNGER', subwords: [ 'YOU', 'YOUR', [length]: 2 ] },
    [length]: 2
  ]
}

CodePudding user response:

You can use arrayFilters update option as follow:

db.collection.update({},
{
  $push: {
    "words.$[x].subwords": "AT"
 }
},
{
 arrayFilters: [
 {
  "x.word": "RATIONAL"
 }
]
})

Explained:

Define arrayFilter x to match the word entry in which you will push the AT value to subwords array

Playground

  • Related