2

我在 mongo 上有一个数据集,例如:

{"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"}

我正在尝试使用 monger 从中获取最短日期,但没有任何运气。

我能做的最好的事情是使用以下方法得出不同的月份和年份:

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

结果如下:

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

然后我使用 clojure 库来获取最小日期。有没有直接使用monger的方法?

4

1 回答 1

0

要在 monger 中执行此操作,您可以先按年份升序对结果进行排序,然后按月份升序对结果进行排序,然后选择第一个结果。

这是文档中的修改示例:

(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))

如果这是您经常做的事情,请考虑向集合中添加索引以加快查询速度:

(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)))
于 2016-09-14T11:34:18.680 回答