首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Clojure - Monger运算符-缺少日期转换的多个字段连接和查询支持

Clojure - Monger运算符-缺少日期转换的多个字段连接和查询支持
EN

Stack Overflow用户
提问于 2016-09-13 14:38:28
回答 1查看 109关注 0票数 2

我有一个关于mongo的数据集,比如:

代码语言:javascript
复制
{"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的最小日期,但没有任何运气。

我能做的最好的事情就是用以下命令计算出不同的月份和年份:

代码语言:javascript
复制
(mc/aggregate mongo-connection collection-name [{$group { :_id { :month "$month", :year "$year" } } }]))

这给出了如下结果:

代码语言:javascript
复制
[{"_id":{"year":2016,"month":11}},
 {"_id":{"year":2016,"month":10}},
 {"_id":{"year":2016,"month":9}}]

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

EN

回答 1

Stack Overflow用户

发布于 2016-09-14 19:34:19

要在monger中做到这一点,您可以首先按年升序对结果进行排序,然后按月升序排序,然后选择第一个结果。

下面是来自documentation的修改后的示例

代码语言:javascript
复制
(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以加快查询速度:

代码语言:javascript
复制
(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)))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39463641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档