Upserts seem to not do what the documentation describes

27 views
Skip to first unread message

Stefan Dorunga

unread,
Feb 17, 2015, 8:06:17 AM2/17/15
to clojure...@googlegroups.com
So I'm trying to use the upsert functionality which the documentation describes as follows

;; updates score for player "sam" if it exists; creates a new document otherwise
(mc/update db "scores" {:player "sam"} {:score 1088} {:upsert true})

When I attempt to replicate this I get two instances of my document without storing the :player field

(ns monger-test.core
(:require  [monger.core :as mg]
           [monger.collection :as mc]))

(def conn  (mg/connect))
(def db  (mg/get-db conn "monger-test"))

(defn update-or-create [user]
  (mc/upsert db "users"  {:username user}  {  :flavour "vanilla" }))

(defn all-users [] (mc/find-maps db "users"))

(defn foo
  "I would expect to get only one user"
  []
  (update-or-create "Joe")
  (update-or-create "Joe")
  (println (all-users))
  )


That is the way I tried it which at the end returns

({:_id #<ObjectId 54e33b7a5a4847fc7da4af65>, :flavour vanilla} {:_id #<ObjectId 54e33b7a5a4847fc7da4af66>, :flavour vanilla})

Am I doing something wrong or does the function not work properly? I haven't found any info about this anywhere else so I fully expect to be doing something wrong.

Any help is really appreciated

Michael Klishin

unread,
Feb 17, 2015, 8:12:03 AM2/17/15
to clojure...@googlegroups.com, Stefan Dorunga
 On 17 February 2015 at 16:11:01, Stefan Dorunga (stefan...@gmail.com) wrote:
> Am I doing something wrong or does the function not work properly?
> I haven't found any info about this anywhere else so I fully expect
> to be doing something wrong.

Update replaces the entire document in MongoDB. If you want to only update
1 field, use the $set operator.
--
@michaelklishin, github.com/michaelklishin

Stefan Dorunga

unread,
Feb 17, 2015, 8:13:37 AM2/17/15
to clojure...@googlegroups.com, stefan...@gmail.com
This is an update with the upsert flag. And I'm only using it since it's the example in the doc. But the source code also has an actual `upsert` method that is just a wrapper for the update with an upsert flag.
Reply all
Reply to author
Forward
0 new messages