1

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: 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.

2 Answers 2

3

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

this was just what I was looking for
1

Yes, you can use UpdateMany() instead of UpdateOne(). See https://www.mongodb.com/blog/post/quick-start-csharp-and-mongodb--update-operation and https://mongodb.github.io/mongo-csharp-driver/2.9/apidocs/html/M_MongoDB_Driver_IMongoCollectionExtensions_UpdateMany__1.htm for more details.

1 Comment

I mean if I can update every item in the list in a different document in the collection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.