Mongodb - 如何在c#中编写Push Upsert?

时间:2016-02-02 17:18:52

标签: c# mongodb

我想通过c#实现以下命令。我已经看过Update.PushAll命令,但我不确定它是否正确。有什么建议吗?

db.students.update(
   { name: "joe" },
   { $push: { scores: { $each: [ 90, 92, 85 ] } } }
, upsert = true
)

1 个答案:

答案 0 :(得分:1)

您可以使用PushAllWrapped在现有文档中添加一系列分数:

var collection = db.GetCollection<Student>("students");
var query = Query<Product>.EQ(p => p.Name, "joe");
var push = Update<Student>.PushAllWrapped<int>(p => p.Scores, newScores);
collection.Update(query, push, UpdateFlags.Multi);

使用新语法,您可以使用PushEach

var collection = db.GetCollection<Student>("students");
var filter = Builders<Students>.Filter.Eq("name", "joe");
var update = Builders<Students>.Update.PushEach<Score>(x=>x.Scores, scores);
await collection.UpdateOneAsync(filter, update);