I'm currently upgrading my code to MongoDB C# driver 2.0 and I'm having issues upgrading the code to update documents.
using the old version I was able to do something like this:
MyType myObject; // passed in var collection = _database.GetCollection<MyType>("myTypes"); var result = collection.Save(myObject);
I'm struggling to find a way to do this in the new version. I have found a few examples of updating single fields like
var filter = Builders<MyType>.Filter.Eq(s => s.Id, id); var update = Builders<MyType>.Update.Set(s => s.Description, description); var result = await collection.UpdateOneAsync(filter, update);
I'd like to update all the fields as I was doing in the old version with the method Save.
Any ideas ?
Thanks a lot
The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.
Welcome to the documentation site for the official MongoDB C++ driver. You can add the driver to your application to work with MongoDB using the C++11 or later standard.
MongoDB is a NoSQL database that is open source. MongoDB is available in two editions. One is MongoDB Open Source, which is free as part of the Open-Source Community, but for the other editions, you must pay a License fee. When compared to the free edition, this edition has some advanced features.
I think you're looking for ReplaceOneAsync()
:
MyType myObject; // passed in var filter = Builders<MyType>.Filter.Eq(s => s.Id, id); var result = await collection.ReplaceOneAsync(filter, myObject)
To add to mnemosyn's answer, while a simple ReplaceOneAsync
does update a document it isn't equivalent to Save
as Save
would also insert the document if it didn't find one to update.
To achieve the same behavior with ReplaceOneAsync
you need to use the options parameter:
MyType myObject; var result = await collection.ReplaceOneAsync( item => item.Id == id, myObject, new UpdateOptions {IsUpsert = true});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With