I couldn't figure out insert to a sub array...
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);
Update Documents in an ArrayThe positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.
If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.
To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With