2

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"]
}
1
  • Could you please provide an example simulating data. It's not necessary real data. Commented Feb 4, 2021 at 18:58

1 Answer 1

1

Maybe something like this:

 db.store.update({},{$push:{"products.$[].$[k]":"value3"}},{ arrayFilters: [{ k:'productId' }]})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it worked. I have one more question though. Now, I wanted to find array containing matching "productId" in the same document as matching "sale". I didn't find much in the mongo documentation regarding this.

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.