简体   繁体   中英

What is best way to update entity?

I am creating application using C# and mongoDB. I have implemented repository pattern for data related operation in mongoDB.

However I am looking for efficient way to update entity in mongoDB. Currently we are getting document by using GetByID method, then do the manipulation in memory and then call save method which updates document in MongoDB server.

Participant p = await participantRepo.GetByIdAsync(ParticipantId);
p.SetCreateAuditInfo(user.Id);
p.AddRelation(user.Id);
participantRepo.SaveAsync(p);

But since we are loading document in memory, it does not look like appropriate way when document is too large or huge. Is there a way to directly update document in MongoDB Server

There are a lot of functions available to update parts of an existing mongodb document.

An example from the docs ( http://mongodb.github.io/mongo-csharp-driver/2.7/reference/driver/crud/writing/ ):

var filter = new BsonDocument("FirstName", "Jack");
var update = Builders<BsonDocument>.Update.Set("FirstName", "John");

(as always there's also a typed version available).

You'll find a list of available operators here: https://docs.mongodb.com/manual/reference/operator/update/

You will find these operators when you take a look at the update builder class in c#. Here's an example for the "set" operator.

var update = Builders<YourModelClass>.Update.Set(_ => _.Name, "new name");
yourMongoCollection.UpdateOneAsync(_ => _.Id, update);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM