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 ライブラリを使用しています。モンガーを使用する直接的な方法はありますか?

4

1 に答える 1

0

モンガーでこれを行うには、最初に結果を年の昇順で並べ替え、次に月の昇順で並べ替えてから、最初の結果を選択します。

ドキュメントから変更された例を次に示します。

(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 に答える