在Monger中有一個insert-and-return
函數用於返回新插入的文檔。與Monger聯繫更新文檔
沒有update-and-return
功能。
如何從執行更新的函數返回更新的文檔?
我想我可以使用save-and-return
,但在我看來,我不能使用此功能的運營商,如$push
。
在Monger中有一個insert-and-return
函數用於返回新插入的文檔。與Monger聯繫更新文檔
沒有update-and-return
功能。
如何從執行更新的函數返回更新的文檔?
我想我可以使用save-and-return
,但在我看來,我不能使用此功能的運營商,如$push
。
我可以看到兩個選項給你。
第一種選擇是使用JohnnyHK's solution與find-and-modify
功能:
(mc/find-and-modify "users"
(select-keys my-doc [:_id])
{ $push { :awards { :award "IBM Fellow"
:year 1963
:by "IBM" }}}
:return-new true)
第二個選擇是使用save
而不是update
。如果您已經從mongodb加載完整文檔,這是一個不錯的選擇。您可以很容易地用clojure
函數替代像$push
這樣的mongodb運算符,如update-in。用clojure地圖操作似乎對我來說是更好的方法。如果您在爲MongoDB操作員找到clojure替代品時遇到問題,我可以幫助您。
對於我前面的例子將是這樣的:
(mc/save-and-return "users"
(update-in my-doc [:awards] conj
{ :award "IBM Fellow"
:year 1963
:by "IBM" }))
我自己,我更喜歡這種方式,因爲它看起來更加的Clojure十歲上下。
這是Monger的find-and-modify
功能的目的。
;; 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)
謝謝。我接受了列昂尼德的回答,因爲他的聲譽較低,他將會獲得更多的賞金。因爲我不能接受這兩個答案,所以我至少投了你的票。希望這對你很好。 – tobiasbayer
@CodeBrickie我不能說我同意,因爲列昂尼德基本上抄錄了我的答案,但正如Obiwan所說:「當然,你必須做你認爲正確的事情。」 – JohnnyHK
他複製你的並添加了第二個選項。所以他也產生了很大的價值。 – tobiasbayer