21

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

2 Answers 2

32

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);
Sign up to request clarification or add additional context in comments.

2 Comments

what should i write behalf of string
you can skip the "String" in Push<String> as it can be inferred from the specified datatype in update field (e.MyArray)
18

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.

2 Comments

thanks. But for Update.PushWrapped what should I reference... Intellicense is not seeing it...
I think it is now ... new UpdateBuilder().PushWrapped in the new version

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.