Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update subarray #471

Closed
martiera opened this issue Nov 24, 2016 · 4 comments
Closed

Update subarray #471

martiera opened this issue Nov 24, 2016 · 4 comments

Comments

@martiera
Copy link

martiera commented Nov 24, 2016

Hello, can't insert subarray, maybe I'm doing something wrong. Can you point me how to do in correct way?
Example of data structure:
{ _id: 'id6', fruits: [{name:'orange', size:['small']},{name:‘pear’, size:[]}, {name: ‘apple’, size: ['small', ‘medium']} ] }

db.update({ _id: 'id6', "fruits.name": 'pear' }, { $addToSet: { "fruits.size" : "medium" } }, {}, function(err, numReplaced) {
console.log('Replaced: %s', numReplaced)
})

Console show:
Replaced: 1

db is not updated.

@Loksly
Copy link

Loksly commented Nov 25, 2016

Hi martiera,
the $addToSet needs to know what is the subdocument you want to change.

db.update({ _id: 'id6', "fruits.name": 'pear' }, { $addToSet: { "fruits.1.size" : "medium" } }, {}, next);

I don't know how to help you to discover what is the number of the subelement inside fruits without a get before the update.

Check this example:
https://jsfiddle.net/yzr1f9ec/

@martiera
Copy link
Author

Thank you! That way it works.

@neody
Copy link

neody commented Sep 25, 2017

how to find fruits.1.size?

@JamesMGreene
Copy link
Contributor

@neody: In their case above, I think that may just be a known target index. However, if you are looking for general support of positional array operations, you may want to check out existing PR #438.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants