LoginSignup
16
16

More than 5 years have passed since last update.

MongoDBで総カウント数とユニークカウント数を知りたい時

Posted at

いつもここからみたいなタイトルになってしまいましたが、よく忘れるので、備忘も兼ねて。。

総数を知りたい時

find()とcount()を使うです。

db.コレクション名.find({条件}, {対象フィールド: 1}).count()

具体的にはこんな感じ。
(5月に男性がダウンロードしたコンテンツの総数)

db.download_histories.find({"sex": "male", "created_at" : { "$gte" : ISODate("2015-05-01T00:00:00+09:00"), "$lte" : ISODate("2015-05-31T23:59:59+09:00") }}, {"contents_id" : 1}).count()

ユニーク数を知りたい時

distinct()とlengthを使うです。

db.コレクション名.distinct({対象フィールド}, {条件}).length

具体的にはこんな感じ。
(5月に男性がダウンロードしたコンテンツのユニーク数)

db.download_histories.distinct("contents_id", {"sex": "male", 
"created_at" : { "$gte" : ISODate("2015-05-01T00:00:00+09:00"), "$lte" : ISODate("2015-05-31T23:59:59+09:00") }}).length

※このクエリはフィクションであり、実在の案件・コレクションとは一切関係ありません

16
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16