Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return updated document with Monger

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.

like image 737
tobiasbayer Avatar asked Jan 04 '13 07:01

tobiasbayer


2 Answers

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)
like image 80
JohnnyHK Avatar answered Sep 18 '22 12:09

JohnnyHK


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.

like image 26
Leonid Beschastny Avatar answered Sep 18 '22 12:09

Leonid Beschastny