In Monger there is a insert-and-return
function for returning a newly inserted document.
There is no update-and-return
function.
How can I return an updated document from the function that executes the update?
I think I could use save-and-return
but it seems to me that I am not able to use operators like $push
with this function.
This is the purpose of Monger's find-and-modify
function.
;; Atomically find the doc with a language of "Python", set it to "Clojure", and
;; return the updated doc.
(mgcol/find-and-modify collection
{:language "Python"}
{:$set {:language "Clojure"} }
:return-new true)
I can see two options for you.
First option is to use JohnnyHK's solution with find-and-modify
function:
(mc/find-and-modify "users"
(select-keys my-doc [:_id])
{ $push { :awards { :award "IBM Fellow"
:year 1963
:by "IBM" }}}
:return-new true)
Second option is to use save
instead of update
. It's a good choice if you already have the entire document loaded from mongodb. You can easily replace mongodb operators like $push
with clojure
functions like update-in. Manipulation with clojure maps seems for me as better approach. If you have problems with finding clojure alternatives for mongodb operators I can help you.
For my previous example it will look like this:
(mc/save-and-return "users"
(update-in my-doc [:awards] conj
{ :award "IBM Fellow"
:year 1963
:by "IBM" }))
Myself, I prefer this way, because it looks more Clojure-ish.
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