Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use $push update modifier in MongoDB and C#, when updating an array in a document

I've run the following code in mongo shell:

db.unicorns.insert({name:  'Dunx',  loves:  ['grape',  'watermelon']});

and now I've something like this in my MongoDB collection:

{name: 'Dunx', loves: ['grape', 'watermelon']}

As you can see loves is an array.

Question

How can I write C# code, with the official C# driver, that does the following:

db.unicorns.update({name: 'Aurora'}, {$push: {loves: 'sugar'}})

The above code runs just fine in mongo shell.

like image 456
Yasser Souri Avatar asked Jul 11 '11 11:07

Yasser Souri


2 Answers

it should be something like this:

unicorns.Update(Query.EQ("name", "Aurora"), Update.Push("loves", "sugar"));
like image 152
Andrei Andrushkevich Avatar answered Oct 20 '22 10:10

Andrei Andrushkevich


I would like to also illustrate how to do it using a different syntax

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

var update = Builders<Unicorn>.Update
        .Push<String>(e => e.Likes, like);

await fantasyContext.Unicorns.FindOneAndUpdateAsync(filter, update);
like image 32
Alex Nolasco Avatar answered Oct 20 '22 09:10

Alex Nolasco