20

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);
Serdar
  • 1,416
  • 2
  • 17
  • 43

2 Answers2

30

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);
Ofir
  • 5,049
  • 5
  • 36
  • 61
19

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.

mnemosyn
  • 45,391
  • 6
  • 76
  • 82