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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Himani Talesara
  • 305
  • 2
  • 8
  • 15

2 Answers2

6

You should use this:

db.collection.update({_id: id1, values: 23}, {$set: {'values.$': 25}})
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • 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. – Gates VP May 11 '12 at 22:32
  • @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. – Himani Talesara May 16 '12 at 07:08
  • @HimaniTalesara: you can run this update repeatedly, or you can fetch the document to the app, modify it there and save back. – Sergio Tulentsev May 16 '12 at 08:40
  • `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". – Gates VP May 16 '12 at 16:46
  • @GatesVP: that won't work if he needs to replace multiple values in the same document. :) – Sergio Tulentsev May 16 '12 at 17:51
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

Community
  • 1
  • 1
DIna AK
  • 29
  • 1
  • 1
  • 5