Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 301
Serdar Avatar asked Dec 02 '11 09:12

Serdar


People also ask

How do you update data in an array of objects in MongoDB?

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.

How do I add elements to an array in MongoDB?

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.

How do I add a field to an existing document in MongoDB?

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 .


2 Answers

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);
like image 199
Ofir Avatar answered Sep 28 '22 12:09

Ofir


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.

like image 23
mnemosyn Avatar answered Sep 28 '22 11:09

mnemosyn