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

血红的双手。 提交于 2019-12-18 14:53:03

问题


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.


回答1:


it should be something like this:

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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/6649174/how-to-use-push-update-modifier-in-mongodb-and-c-when-updating-an-array-in-a

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