I'm trying to add a json map to an array in my database using monger
but there is something wrong. I've found how to do it in monger documentation, but $push
and $addToSet
aren't working:
Here is my function:
(defn add-vehicle [vehicle]
(let [connect-string (System/getenv "MONGO_CONNECTION")
{:keys [conn db]} (mg/connect-via-uri connect-string)]
(mc/update db "drivers-collection"
{:email (:email vehicle)}
{$addToSet {:cars (:vehicle vehicle)}})))
And this is how I'm calling this function in nREPL
:
(add-vehicle {:email "teste111@hotmail.com"
:vehicle {:model "fusca"
:color "rosa"
:plate "AIO-9807"}})
Any ideas?
This is my document in drivers-collection
:
{
"_id": {
"$oid": "57bee61edcba0f2f7559eb56"
},
"email": "teste111@hotmail.com",
"name": "Guilherme Job",
"cars": [],
"customerId": "cus_9O4dhvtuF2926m"
}
My car's array are empty and I'm trying to add a vehicle into it.
Make sure that your query part of monger.collection/update
call contains a correct criteria. You should also inspect the WriteResult
returned by Mongo driver to see if they were successful or not.
I have tested using $push
in REPL and everything works correctly. As you can see a car is added:
(require '[monger.core :as mg])
(require '[monger.collection :as mc])
(require '[monger.operators :refer :all])
(def conn (mg/connect))
(def db (mg/get-db conn "test-db"))
(def coll "test-collection")
(mc/insert db coll {:email "a@example.com" :name "Guilherme Job" :cars []})
(mc/find-maps db coll)
;; => ({:_id #object[org.bson.types.ObjectId 0x58f153ea "580e826e7e92729ffb000611"], :email "a@example.com", :name "Guilherme Job", :cars []})
(mc/update db coll {:email" "a@example.com"} {$push {:cars" {:name "Ford"}}})
(mc/find-maps db coll)
;; => ({:_id #object[org.bson.types.ObjectId 0x494168cd "580e826e7e92729ffb000611"], :email "a@example.com", :name "Guilherme Job", :cars [{:name "Ford"}]})