Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

node.js - 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"]
}
question from:https://stackoverflow.com/questions/66049704/mongo-db-append-a-value-to-a-nested-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Maybe something like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...