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

Serdar picture Serdar · Dec 2, 2011 · Viewed 17.4k times · Source

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);

Answer

Ofir picture Ofir · Dec 26, 2015

Syntax for new MongoDB c# async adapter:

var filter = Builders<myObject>
             .Filter.Eq(e => e.Name, "name");

var update = Builders<myObject>.Update
        .Push<String>(e => e.MyArray, myArrayField);

await collection.FindOneAndUpdateAsync(filter, update);