15

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.

3 Answers 3

19

it should be something like this:

unicorns.Update(Query.EQ("name", "Aurora"), Update.Push("loves", "sugar"));
Sign up to request clarification or add additional context in comments.

2 Comments

How to do this thing currently using C# driver 2.0.0 of mongodb?
@Faraz Ahmad see answer below
12

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

1 Comment

Is there a way that this can be done with Builder<BsonDocument>? If not, what do you need to specify when you define the object (Unicorn in this case)?
0

To do this with the updated syntax and regular BsonDocuments instead of defined objects, use the following:

var filter = Builders<BsonDocument>.Filter.Eq("name": "Aurora");
var update = Builders<BsonDocument>.Update.Push("loves", "sugar"):

// you can also use the async update method from Alex's answer here
var result = fantasyContext.Unicorns.UpdateOne(filter, update);

Comments

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.