我有一个关于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的方法?
发布于 2016-09-14 19:34:19
要在monger中做到这一点,您可以首先按年升序对结果进行排序,然后按月升序排序,然后选择第一个结果。
下面是来自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))如果这是您经常要做的事情,请考虑向集合中添加一个index以加快查询速度:
(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)))https://stackoverflow.com/questions/39463641
复制相似问题