2

I am using Mongodb C# official driver. I want to change a particular value in an array with some other value. The array contains list of values. For eg.

{ 
   _id: id1,
   values: [23, 78, 20]
}

I want suppose to replace 23 by 25. I know one answer if it is right. First I pull that element and then push other. But the problem is that if the element is not present then also push will insert the element. Secondly, it will change the position and insert the element at the end. Please tell me how to do it.

7
  • Read about positional operator Commented May 11, 2012 at 19:48
  • I have read but all examples are about incrementing the value. Commented May 11, 2012 at 19:51
  • well, swap $inc for $set and you're good to go. Commented May 11, 2012 at 19:53
  • I have done it. But it inserts the null in that array.. Commented May 11, 2012 at 20:02
  • I just did it and it worked as expected. There's problem in your code. Commented May 11, 2012 at 20:02

2 Answers 2

6

You should use this:

db.collection.update({_id: id1, values: 23}, {$set: {'values.$': 25}})
Sign up to request clarification or add additional context in comments.

5 Comments

I think you need to add the _id to this answer. Otherwise you will update the first document with a value of 23, which is not what you want.
@GatesVP: Thanks it works. But what to do if I want each occurence of 23 to be replaced by certain number. $ works for first matched.
@HimaniTalesara: you can run this update repeatedly, or you can fetch the document to the app, modify it there and save back.
db.collection.update({values:23}, {$set: {'values.$': 25}}, false, true) That extra false is "do not upsert". That extra true is "perform this update multiple times".
@GatesVP: that won't work if he needs to replace multiple values in the same document. :)
2

This should work with you

db.collection.update({ "_id" : id1 }, {$set: {"values.0": 23}});

check this post as well Update mongo array elements by index with c-driver

Comments

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.