dj-nitehawk / MongoDB.Entities

A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management
https://mongodb-entities.com
MIT License
547 stars 70 forks source link

DB.UpdateAndGet() + "Insert an entity if it doesn't exist" #220

Closed pachanga closed 8 months ago

pachanga commented 8 months ago

Hi!

I was wondering whether it's possible to update and get an entity or insert and retrieve it using one API call, so that it happens atomically on Mongo level?

Something as follows:

var book = await DB.UpdateAndGet<Book>()
    .Match(b => b.ID == "xxxxxxxxxxxxx")
    .Modify(b => b.Title, "updated title")
    .ModifyOnInsert(b  => b.Author, "Bob") // this part is executed only if entity doesn't exist and it's inserted
     .ModifyOnInsert(b  => b.Links, 1) // this part is executed only if entity doesn't exist and it's inserted
    .ExecuteAsync(); 
dj-nitehawk commented 8 months ago

you can do an upsert as shown here: https://github.com/dj-nitehawk/MongoDB.Entities/issues/216#issuecomment-1868503265 but i don't think the mongo driver can do different things depending on whether its an update or insert. i.e. if you upsert, the document/entity will have both author set to bob & links set to 1 in both cases.