2

Using the MongoDB C# Driver version 2.0.1 with Mongodb 3.0, is it possible to use typed methods to update an array field document element?

For example, I have the following document:

{
     Name:"Ken",
     ContactNo:[ { Number:"123", Type:"Mobile"},
                  { Number:"456", Type:"Office"},
                  { Number:"531", Type:"Fax"}
                ]
 }

How do I do the following operations using typed C# methods:

1) Update the Type field for all elements of the ContactNo array to be "PABX"

2) Update ContactNo array document element's Type field whose Number field equals "123" to be "Fiber"

3) Update the first element of the Contact array and set its Type field to be "Unknown"

Donut
  • 110,061
  • 20
  • 134
  • 146
kenalex
  • 61
  • 1
  • 10

1 Answers1

2
  1. It's not currently possible to update all the items in an array using the positional operator. See this StackOverflow question and this MongoDB issue. However, if you know the number of elements in your array ahead of time (or can obtain it somehow), then this will work:

    var numberOfElementsInArray = 3;
    var filter = Builders<Contact>.Filter.Eq("Name", "Ken");
    var update = Builders<Contact>.Update.Combine(Enumerable.Range(0, numberOfElementsInArray)
            .Select(i => Builders<Contact>.Update.Set("ContactNo." + i + ".Type", "PABX")));
    collection.UpdateOneAsync(filter, update).Wait();
    
  2. This code will set the Type property of the element in the ContactNo array with a Number of 123 to Fiber:

    var filter = Builders<Contact>.Filter.And(
            Builders<Contact>.Filter.Eq("Name", "Ken"),
            Builders<Contact>.Filter.Eq("ContactNo.Number", "123"));
    var update = Builders<Contact>.Update.Set("ContactNo.$.Type", "Fiber");
    collection.UpdateOneAsync(filter, update).Wait();
    
  3. This code will set the Type property of the first element in the ContactNo array to Unknown:

    var filter = Builders<Contact>.Filter.Eq("Name", "Ken");
    var update = Builders<Contact>.Update.Set("ContactNo.0.Type", "Unknown");
    collection.UpdateOneAsync(filter, update).Wait();
    

Note that all of this code assumes that you have a class called Contact that corresponds to the data you specified in your question (your actual class might be called something else, I just called it Contact here), and that collection is an instance of IMongoCollection<Contact>.

For example:

var client = new MongoClient("mongodb://localhost:27017");
var collection = client.GetDatabase("your database").GetCollection<Contact>("your collection name");
Community
  • 1
  • 1
Donut
  • 110,061
  • 20
  • 134
  • 146