7

Using MongoDB, I'm having trouble adding en element to an Array when the array is null. AddToSet works as expected if I add the item from the console. I am using the official C# driver from 10gen.

var query = Query.EQ("_id", objectId);          
var itemDoc = item.ToBsonDocument();

//items is an array but currently null
var update = MongoDB.Driver.Builders.Update.AddToSet("items", itemDoc); // YUNoWork?

//somefield doesn't exist
var workingUpdate = MongoDB.Driver.Builders.Update.AddToSet("somefield", itemDoc); //works fine

var collection = DataBase.GetCollection<MyObject>(CollectionName);

collection.Update(query, update); // doesn't work
collection.Update(query, workingUpdate); // works

Is this expected behavior? If so, is there a more general way to add items to an array?

2 Answers 2

14

Did some digging, according to some other comments - like you say, if the element doesn't exist, it works, but if it's null - it doesn't work. Apparently this is by design.

One suggestion was to add the BsonIgnoreIfNull attribute to arrays, which will mean your AddToSet will then work.

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

2 Comments

Using BsonIgnoreIfNull for lists resolves the impedance mismatch between the C# class definitions and MongoDB. Thanks!
Just to clarify for anyone else who sees this answer, you'll have to clean up your existing data for this to work. In other words, if you already have a document with a null property, you'll have to delete the property or the document. Then this will work the next time you use AddToSet. I had added the attribute, but it still didn't work because the data had already been saved with the null.
1

Instead of null value, put an empty array.

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.