0

Say, the existing document in DB is like this:

{
  "_id": "1",
  "settings": {
     "languages": [ "english", "french" ]
  }
}

Now I want to update the document to this:

{
  "_id": "1",
  "settings": {
     "languages": [ "korean", "german" ]
  }
}

I tired this following code:

var lan = new List<string> { "finish", "russian", "korean" }   
collection.UpdateOne(
Builders<MyObject>.Filter.Eq("_id", "1"), 
Builders<MyObject>.Update.Set("settings.languages", lan));

But got following exception:

MongoDB.Bson.Serialization.Serializers.EnumerableInterfaceImplementerSerializer2[System.Collections.Generic.List1[System.String],System.String]' cannot be converted to type 'MongoDB.Bson.Serialization.IBsonSerializer`1[System.String]

I also tried using BsonArray to initialize the new languages array:

var bsonArray = new BsonArray
{
    "korean",
    "german"
};

collection.UpdateOne(
Builders<MyObject>.Filter.Eq("_id", "1"), 
Builders<MyObject>.Update.Set("settings.languages", bsonArray));

The update could be executed without error, but the languages in document is changed to:

{
  "_id": "1",
  "settings": {
     "languages": "[korean, german]"
  }
}

It becomes "[ xx, xx ]", instead of [ "xx", "xx" ]. It is not what I expected.

1 Answer 1

1

You're getting that error message because you're using strongly typed builders on type MyObject which probably looks more or less like below:

public class MyObject
{
    public string _id { get; set; }
    public Settings settings { get; set; }
}

public class Settings
{
    public string[] languages { get; set; }
}

So since you have a strongly typed Builder you are getting an exception because of the type mismatch between List and Array. Two ways to fix that:

Either use .ToArray() on list to get the same type as the one you have in your MyObject:

var lan = new List<string> { "finish", "russian", "korean" };
collection.UpdateOne(
    Builders<MyObject2>.Filter.Eq("_id", "1"),
    Builders<MyObject2>.Update.Set("settings.languages", lan.ToArray()));

or skip the type validation using BsonDocument class:

var collection = mydb.GetCollection<BsonDocument>("col");
var lan = new List<string> { "finish", "russian", "korean" };
collection.UpdateOne(
    Builders<BsonDocument>.Filter.Eq("_id", "1"),
    Builders<BsonDocument>.Update.Set("settings.languages", lan));
Sign up to request clarification or add additional context in comments.

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.