本文介绍了使用mongodb聚合的多个字段的不同计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过一个MongoDB聚合查询来计算多个字段的不同值.

I'm trying to count distinct values of multiple fields By one MongoDB Aggregation query.

这是我的数据:

{
    "car_type": "suv",
    "color": "red",
    "num_doors": 4
},
{
    "car_type": "hatchback",
    "color": "blue",
    "num_doors": 4
},
{
    "car_type": "wagon",
    "color": "red",
    "num_doors": 4
}

我希望每个字段都有不同的计数:

I want a distinct count of each field:

distinct_count_car_type=3
distinct_count_color=2
distinct_count_num_doors=1

我能够对多个字段进行分组,然后进行不同的计数,但是它只能使我对第一个字段计数.不是所有的人.而且这是大量的数据.

I was able to group multiple fields and then do a distinct count but it could only give me a count on the first field. Not all of them.And also it's a large set of data.

推荐答案

您正在寻找... $objectToArray的力量!

You're looking for the power of ... $objectToArray!

db.foo.aggregate([
  {$project: {x: {$objectToArray: "$$CURRENT"}}}
  ,{$unwind: "$x"}
  ,{$match: {"x.k": {$ne: "_id"}}}
  ,{$group: {_id: "$x.k", y: {$addToSet: "$x.v"}}}
  ,{$addFields: {size: {"$size":"$y"}} }
                    ]);

这将产生:

{ "_id" : "num_doors", "y" : [ 4 ], "size" : 1 }
{ "_id" : "color", "y" : [ "blue", "red" ], "size" : 2 }
{
    "_id" : "car_type",
    "y" : [
        "wagon",
        "hatchback",
        "suv"
    ],
    "size" : 3
}

您可以视情况选择$project$addFields包括或排除一组唯一值或大小.

You can $projector $addFieldsas you see fit to include or exclude the set of unique values or the size.

这篇关于使用mongodb聚合的多个字段的不同计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 04:23