问题
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 BsonDocument
s 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