2

so I have this mongoose schema:

schema = mongoose.Schema({
    identifier: Number,
    shopItems: [{
         identifier: Number,
         price: Number
    }]
});

now I know how to push new items to this collections shopItems array with{ $push { shopItems { identifier: id, price: price } }.

But now I want to update an item in the shopItems array with a specific identifier value, is that possible?

I was thinking that this would work: { $push { "shopItems.identifier": myVal, price: newPrice } } but it didnt, so I am really lost.

4
  • Do you have a old value for a identifier to identify its position in shopItems array ? If yes you can use positional operator to update the identifier at that position with new element. Something like find and replace in array. db.collection_name.update({"shopItems.identifier": id}, {"$set":{"shopItems.$":{identifier:myVal, price: newPrice }}}) Commented Sep 23, 2017 at 14:23
  • @Veeram yes I do have a value for the identifier, I want to find the item in the array with the correct identifier and update its prices. Commented Sep 23, 2017 at 14:27
  • Use this if you only like to update prices. db.collection_name.update({"shopItems.identifier": myVal}, {"$set":{"shopItems.$.price: newPrice }}) Commented Sep 23, 2017 at 14:28
  • @Veeram thank you! :) Commented Sep 23, 2017 at 14:30

1 Answer 1

1

You can achieve this as follows:

db.collection.update({'shopItems.identifier' : myVal }, { $set : { 'shopItems.$.price' : newPrice}});
Sign up to request clarification or add additional context in comments.

2 Comments

It is not working for me. I am getting Invalid BSON field name.
how do i do for multiple object?

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.