Search code examples
c#mongodbmongodb-.net-driver

How can I update mongodb document for adding a new item to array?


I couldn't figure out insert to a sub array...

  • _id
  • MyArray
  • --Item
  • ----ArrayItemId
  • ----Name

I want to insert items to MyArray...

How my update document should be?

MyCollection.Update( 
 new QueryDocument { { "_id", MyObject.Id } },
 new UpdateDocument { { "$set", new BsonDocument { { "MyArray", 
       new BsonArray { new BsonDocument {{ "ArrayItemId", myArrayField.Id }},
                       new BsonDocument {{ "Name", myArrayField.Name }} }}}}}, 
 UpdateFlags.None);

Solution

  • Inserting in an array is done using the $push operator.

    As a side note, you don't need to use QueryDocument and UpdateDocument. There's a much easier helper syntax:

    MyCollection.Update(Query.EQ("_id", MyObject.Id), 
                        Update.PushWrapped("MyArray", myArrayField)
    

    Note that PushWrapped<T> allows to push documents, while Push accepts only such types that can be represented by a simple field in MongoDB.