Ashish
Ashish

Reputation: 31

Mongo DB: Append a value to a nested array

I think there might be better ways to store data but the app I am working on has some data stored like this.

I have a document with nested arrays. In this particular example, would it be possible to append a new element "value3" to an array inside products whose "productId" matches the condition. So, basically look for productId and append "value3" to the array which has matching "productId".

I am just learning about MongoDB so if you can provide some suggestions for changing schema, even that would be very helpful.

P.S. Not sure if it helps but I am using node.js

{"_id":
    {"$oid":"601baf0e5c307422c0fa958c"},
    "sale":"Test Sale",
    "products":[
      [
        ["productId","value1","value2"],
        ["productId","value1","value2"]
      ],
      [
        ["productId","value1","value2"],
        ["productId","value1","value2"]
      ],
      [
        ["productId","value1","value2"],
        ["productId","value1","value2"]
      ]
    ],
    "collectionProducts":["id","id","id"]
}

Upvotes: 2

Views: 473

Answers (1)

R2D2
R2D2

Reputation: 10697

Maybe something like this:

 db.store.update({},{$push:{"products.$[].$[k]":"value3"}},{ arrayFilters: [{ k:'productId' }]})

Upvotes: 1

Related Questions