C#MongoDB更新/Upsert列表< Object>到收藏 [英] C# MongoDB Update / Upsert List<Object> to Collection
问题描述
我正在寻找一种在MongoDB中更新/更新到MongoDB集合中的项目列表的方法.
I was searching for a way to Update / Upsert in MongoDB a List of items to a MongoDB collection.
有没有办法做到这一点,或者我必须使用循环来逐项更新项目?
Is there any way to do it or I have to use a loop to update the items one by one?
P.S:问题不是制作一种可以完成作业的方法(一个接一个),但我想避免MongoDB数据库的过多迭代.
P.S: The problem is not making a method that would do the Job (one by one) but I want to avoid too much iterations with the MongoDB database.
这是我当前正在使用的方法:
Here's the method that I'm currently using:
public static void UpdateAll()
{
var client = new MongoClient("mongodb://server_ip:27017");
var db = client.GetDatabase("M_PROJECT");
var collection = db.GetCollection<Product>("products");
//Config.Products is a List<Product> that was previously retrieved from the same collection in MongoDB
foreach(Product product in Config.Products)
{
var filter = Builders<Product>.Filter.Eq(p => p.ID, product.ID);
var update = Builders<Product>.Update.Set("Name", product.Name).Set("Price", 20);
collection.UpdateOne(filter, update, new UpdateOptions() { IsUpsert = true });
}
}
也许没有指定我要更新的每个字段/属性,而只是应用了类实例.
And maybe without specifying every Field/Property that I want to update, but just applying the class instance.
推荐答案
尝试批量替换,如下所示:
try a bulk replace like so:
var models = new List<WriteModel<Product>>();
foreach (var product in Config.Products)
{
if (product.ID == null) product.ID = ObjectId.GenerateNewId();
var upsert = new ReplaceOneModel<Product>(
filter: Builders<Product>.Filter.Eq(p => p.ID, product.ID),
replacement: product)
{ IsUpsert = true };
models.Add(upsert);
}
collection.BulkWrite(models);
这里要注意的事情是,它将使用您的产品类实例中的数据完全覆盖db中存储的数据.但我认为您会没事的,因为您说这些产品是从同一收藏中检索到的.
the thing to note here is that it will completely overwrite the data stored in the db with the data from your product class instances. but i think you'd be okay cause you said the products are retrieved from the same collection.
this is what my library MongoDB.Entities does internally to achieve products.Save()
这篇关于C#MongoDB更新/Upsert列表< Object>到收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!