2

I have a data set on mongo like:

{"month": 9, "year": 2015, "name": "Mr A"}
{"month": 9, "year": 2015, "name": "Mr B"}
{"month": 10, "year": 2015, "name": "Mr B"}
{"month": 11, "year": 2016, "name": "Mr B"}

I am trying to get the minimum date from this using monger, but without any luck.

The best i could do was coming up with distinct month and year using:

(mc/aggregate mongo-connection collection-name [{$group { :_id { :month "$month", :year "$year" } } }]))

Which gave result like:

[{"_id":{"year":2016,"month":11}},
 {"_id":{"year":2016,"month":10}},
 {"_id":{"year":2016,"month":9}}]

And then I am using clojure libraries to get minimum date. Is there any direct way using monger?

Mrinal Saurabh
  • 948
  • 11
  • 16

1 Answers1

0

To do this in monger you could sort the result first by year ascending, then month ascending, then pick the first result.

Here's a modified example from the documentation:

(ns my.service.server
  (:refer-clojure :exclude [sort find])
  (:require [monger.core :as mg]
            [monger.query :refer :all]))

(let [conn (mg/connect)
      db   (mg/get-db "your-db")
      coll "your-coll"]
  (with-collection db coll
    (find {})
    (fields [:year :month])
    ;; it is VERY IMPORTANT to use array maps with sort
    (sort (array-map :year 1 :month 1))
    (limit 1))

If this is something you will do often, consider adding an index to the collection to speed up the query:

(ns my.app
  (:require [monger.core :as mg]
            [monger.collection :as mc]))

(let [conn (mg/connect)
      db   (mg/get-db "your-db")
      coll "your-collection"]

  ;; create an index on multiple fields (will be automatically named year_1_month_1 by convention)
  (mc/ensure-index db coll (array-map :year 1 :month 1)))
ASRye
  • 19
  • 1
  • 1