0

I have a document which is structured like this

{    vendor_id:534534
    ItemList:[
    {"Brand": "Apple","Product": "iPad"},
    {"Brand": "Samsung","Product": "Galaxy"},
    {"Brand": "Apple","Product": "iPhone"}
    ]
}

I want to update the document in my array ItemList, to add a new field say model to only one particular document to make my document look like

{    vendor_id:534534
        ItemList:[
        {"Brand": "Apple","Product": "iPad","Model":"Air2"},
        {"Brand": "Samsung","Product": "Galaxy"},
        {"Brand": "Apple","Product": "iPhone"}
        ]
    }

I know using $addToSet/$push can directly add to the array itself, but how to add can I add it to the document within the array.

This is different because you don't have a key to identify which document in the array you need to update. If there happens to be a key, I too know the answer :)

Ajay Srikanth
  • 1,095
  • 4
  • 22
  • 43
  • In your query, use [`$elemMatch`](https://docs.mongodb.org/manual/reference/operator/query/elemMatch/#op._S_elemMatch) with whatever combination of subdoc fields you need to uniquely identity the element to update. e.g. `ItemList: {$elemMatch: {"Brand": "Apple", "Product": "iPhone"}}`. So you do have a key, it's just multiple fields. – JohnnyHK Apr 29 '16 at 22:19
  • Are you using native driver ? If you are, i have a solution, i never messed around with mongoose and such. – AJ_ Apr 30 '16 at 02:27
  • Yes John, I'm just trying to achieve this in the mongo shell, so that I can convert that to my .net code – Ajay Srikanth Apr 30 '16 at 02:57
  • I found the answer here http://stackoverflow.com/questions/22588236/how-to-add-an-extra-field-in-a-sub-document-in-mongodb – Ajay Srikanth Apr 30 '16 at 04:34

0 Answers0