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

Yasser Souri picture Yasser Souri · Jul 11, 2011 · Viewed 11.1k times · Source

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.

Answer

Andrei Andrushkevich picture Andrei Andrushkevich · Jul 11, 2011

it should be something like this:

unicorns.Update(Query.EQ("name", "Aurora"), Update.Push("loves", "sugar"));