web-dev-qa-db-ja.com

mongodbは、フィールド/キーごとの個別の値の数をカウントします

DBにフィールドに含まれる個別の値の数を計算するクエリはありますか。

f.e国のフィールドがあり、国の値には8種類あります(スペイン、イングランド、フランスなど)

誰かが新しい国でさらにドキュメントを追加した場合、クエリは9を返します。

グループ化してカウントするより簡単な方法はありますか?

81
Liatz

MongoDBには distinctコマンド があり、フィールドの個別の値の配列を返します。配列の長さでカウントを確認できます。

シェルもあります db.collection.distinct() ヘルパー:

> db.countries.distinct('country');
[ "Spain", "England", "France", "Australia" ]

> db.countries.distinct('country').length
4
162
Stennie

集約APIの使用例を次に示します。ケースを複雑にするために、ドキュメントの配列プロパティから大文字と小文字を区別しない単語でグループ化しています。

db.articles.aggregate([
    {
        $match: {
            keywords: { $not: {$size: 0} }
        }
    },
    { $unwind: "$keywords" },
    {
        $group: {
            _id: {$toLower: '$keywords'},
            count: { $sum: 1 }
        }
    },
    {
        $match: {
            count: { $gte: 2 }
        }
    },
    { $sort : { count : -1} },
    { $limit : 100 }
]);

そのような結果を与える

{ "_id" : "inflammation", "count" : 765 }
{ "_id" : "obesity", "count" : 641 }
{ "_id" : "epidemiology", "count" : 617 }
{ "_id" : "cancer", "count" : 604 }
{ "_id" : "breast cancer", "count" : 596 }
{ "_id" : "apoptosis", "count" : 570 }
{ "_id" : "children", "count" : 487 }
{ "_id" : "depression", "count" : 474 }
{ "_id" : "hiv", "count" : 468 }
{ "_id" : "prognosis", "count" : 428 }
89
expert

MongoDb 3.4.4以降では、$arrayToObject演算子と$replaceRootパイプラインでカウントを取得します。

たとえば、異なるロールを持つユーザーのコレクションがあり、ロールの個別のカウントを計算するとします。次の集約パイプラインを実行する必要があります。

db.users.aggregate([
    { "$group": {
        "_id": { "$toLower": "$role" },
        "count": { "$sum": 1 }
    } },
    { "$group": {
        "_id": null,
        "counts": {
            "$Push": { "k": "$_id", "v": "$count" }
        }
    } },
    { "$replaceRoot": {
        "newRoot": { "$arrayToObject": "$counts" }
    } }    
])

出力例

{
    "user" : 67,
    "superuser" : 5,
    "admin" : 4,
    "moderator" : 12
}
13
chridam

Mongo Shell Extensions を活用できます。 Node.js/io.jsでコーディングしている場合は、$HOME/.mongorc.jsに、またはプログラムで追加できる単一の.jsインポートです。

サンプル

フィールドの個別の値ごとに、オプションでクエリでフィルタリングされたドキュメント内の出現回数をカウントします

> db.users.distinctAndCount('name', {name: /^a/i})

{
  "Abagail": 1,
  "Abbey": 3,
  "Abbie": 1,
  ...
}

フィールドパラメータは、フィールドの配列にすることができます

> db.users.distinctAndCount(['name','job'], {name: /^a/i})

{
  "Austin,Educator" : 1,
  "Aurelia,Educator" : 1,
  "Augustine,Carpenter" : 1,
  ...
}
8
evandrix

コレクション内のfield_1で個別を見つけるが、次のようにできるよりもいくつかのWHERE条件も必要です。

db.your_collection_name.distinct('field_1', {WHERE condition here and it should return a document})

したがって、年齢が25歳を超えるコレクションから、異なる番号namesを見つけます。

db.your_collection_name.distinct('names', {'age': {"$gt": 25}})

それが役に立てば幸い!

4
Vimal