我有一个关于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"}
我试图从这个using 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中,您可以先按年升序排序,然后按月升序排序,然后选择第一个结果
下面是文档中修改后的示例:
(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)))