15

Is there a query to update sc from 15 to let's say 17 for array element with id 2 for _id 1? I've this structure in mongodb:

  { _id: 1,
    lb: [
       {
          id: 2,
          sc: 15
       },
       {
          id: 3,
          sc: 16
       }
        ]
  }
  { _id: 2,
    lb: [
       {
          id: 5,
          sc: 34
       },
       {
          id: 6,
          sc: 12
       }
        ]
  }

I have one more: is there a way to write a query to update as you just said and if there is no array element with updated id, insert a new one. I don't want to make two queries - first to check if element exist and update it, second to append it if there is no such. It would be nice to append it in one query. Thanks. – user3045201 1 hour ago

3
  • Isn't it the element with id 1 in your example? sc is 15 for the first element of your array. Commented Nov 28, 2013 at 9:39
  • Yes and I want it to be 17 Commented Nov 28, 2013 at 9:43
  • You should generalise your question's example Commented Jun 23, 2020 at 7:31

1 Answer 1

38

You can update it using the following query :

db.myCollection.update({"_id" : 1, "lb.id" : 2},{$set : {"lb.$.sc" : 17}})

AFAIK, It is not possible to do what you want in a single query. You have to make seperate queries for each of them.

Sign up to request clarification or add additional context in comments.

2 Comments

You are welcome. I have updated my answer for your second question. Also if it worked, you can mark it as an answer.
I tried this and got "The dollar ($) prefixed field '$set' in '$set' is not valid for storage." -- am using golang+mongo

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.