How can I execute a Mongo `forEach` (or run my own JS) with Monger?

417 Views Asked by At

I'm using Monger to connect to Mongo. I want to run

db.collection.find().forEach(function(x) { db.collection-two.insert(...) })

I can't see a relevant 'for each' entry in the Monger docs or a way to pass in JavaScript to insert into another collection. How do I do this?

EDIT this question was based on a misunderstanding (forEach lies in the client API not on the server API). I would delete it but I can't.

2

There are 2 best solutions below

0
On

You can use command function from monger and eval mongodb command

(ns user
  (:require [monger.core :as mg]
            [monger.core :as mc]))

;; (command {:eval "function() { db.collection.find().forEach() }"}

(mg/connect!)
(mg/set-db! (mg/get-db "test"))
(mc/command {:eval "function() { db.fs.files.find().forEach(function(x) { })}"})
3
On

You can process each document as a lazy sequence of Clojure maps:

(require 'monger.collection)

(doseq [x (monger.collection/find-maps "your-collection")]
  ;you can process x here, which is a vanilla clojure map
  (println x))

Why are you trying to use JavaScript? Are you using ClojureScript, or are you just thinking in terms of how you would write code from the mongodb shell?

Disclaimer: Using doseq here is not functional, and probably not idiomatic depending on what you are trying to accomplish. Using map or reduce is probably better, I was just trying to write something that most closely aligned with your forEach example code.

Related: