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

拜拜、爱过 提交于 2019-11-30 11:41:32

it should be something like this:

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

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!