mongodbclojuremonger

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.


Solution

  • 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.